home *** CD-ROM | disk | FTP | other *** search
/ PC World 2007 December / PCWorld_2007-12_cd.bin / v cisle / htttrack / httrack-3.41-3.exe / {app} / src / htslib.c < prev    next >
C/C++ Source or Header  |  2007-06-15  |  159KB  |  5,573 lines

  1. /* ------------------------------------------------------------ */
  2. /*
  3. HTTrack Website Copier, Offline Browser for Windows and Unix
  4. Copyright (C) Xavier Roche and other contributors
  5.  
  6. This program is free software; you can redistribute it and/or
  7. modify it under the terms of the GNU General Public License
  8. as published by the Free Software Foundation; either version 2
  9. of the License, or any later version.
  10.  
  11. This program is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with this program; if not, write to the Free Software
  18. Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
  19.  
  20.  
  21. Important notes:
  22.  
  23. - We hereby ask people using this source NOT to use it in purpose of grabbing
  24. emails addresses, or collecting any other private information on persons.
  25. This would disgrace our work, and spoil the many hours we spent on it.
  26.  
  27.  
  28. Please visit our Website: http://www.httrack.com
  29. */
  30.  
  31.  
  32. /* ------------------------------------------------------------ */
  33. /* File: Subroutines                                            */
  34. /* Author: Xavier Roche                                         */
  35. /* ------------------------------------------------------------ */
  36.  
  37. /* Internal engine bytecode */
  38. #define HTS_INTERNAL_BYTECODE
  39.  
  40. // Fichier librairie .c
  41.  
  42. #include "htscore.h"
  43.  
  44. #ifdef _WIN32_WCE
  45. #ifndef HTS_CECOMPAT
  46. #pragma comment(lib, "celib.lib") //link with celib
  47. #endif
  48. #endif
  49.  
  50. /* specific definitions */
  51. #include "htsbase.h"
  52. #include "htsnet.h"
  53. #include "htsbauth.h"
  54. #include "htsthread.h"
  55. #include "htsback.h"
  56. #include "htswrap.h"
  57. #include "htsmd5.h"
  58. #include "htsmodules.h"
  59.  
  60. #ifdef _WIN32
  61. #ifndef  _WIN32_WCE
  62. #include <direct.h>
  63. #endif
  64. #else
  65. #ifdef HAVE_SYS_TYPES_H
  66. #include <sys/types.h>
  67. #endif
  68. #ifdef HAVE_SYS_STAT_H
  69. #include <sys/stat.h>
  70. #endif
  71. #ifdef HAVE_UNISTD_H
  72. #include <unistd.h>
  73. #endif
  74. #endif  /* _WIN32 */
  75.  
  76. #include <string.h>
  77. #include <time.h>
  78.  
  79. #ifndef  _WIN32_WCE
  80. #include <sys/timeb.h>
  81. #include <fcntl.h>
  82. #else
  83. #ifndef HTS_CECOMPAT
  84. #include <sys/timeb.h>
  85. #endif
  86. #endif  /* _WIN32_WCE */
  87.  
  88. // pour utimbuf
  89. #ifdef _WIN32
  90. #ifndef _WIN32_WCE
  91. #include <sys/utime.h>
  92. #else
  93. #ifndef HTS_CECOMPAT
  94. #include <sys/utime.h>
  95. #endif
  96. #endif
  97. #else
  98. #include <utime.h>
  99. #endif  /* _WIN32 */
  100.  
  101. #ifndef _WIN32_WCE
  102. #include <sys/stat.h>
  103. #endif
  104. /* END specific definitions */
  105.  
  106.  
  107. // Debugging
  108. #if _HTS_WIDE
  109. FILE* DEBUG_fp=NULL;
  110. #endif
  111.  
  112. /* variables globales */
  113. int _DEBUG_HEAD;
  114. FILE* ioinfo;
  115.  
  116. #if HTS_USEOPENSSL
  117.  SSL_CTX *openssl_ctx = NULL;
  118. #endif
  119. int IPV6_resolver = 0;
  120.  
  121. /* dΘtection complΘmentaire */
  122. const char* hts_detect[] = {
  123.   "archive",
  124.   "background",
  125.   "data",         // OBJECT
  126.   "dynsrc",
  127.   "lowsrc",
  128.   "profile",      // element META
  129.   "src",
  130.   "swurl",
  131.   "url",
  132.   "usemap",
  133.   "longdesc",     // accessibility
  134.   "xlink:href",   // xml/svg tag
  135.   ""
  136. };
  137.  
  138. /* dΘtecter dΘbut */
  139. const char* hts_detectbeg[] = {
  140.   "hotspot",      /* hotspot1=..,hotspot2=.. */
  141.   ""
  142. };
  143.  
  144. /* ne pas dΘtcter de liens dedans */
  145. const char* hts_nodetect[] = {
  146.   "accept-charset",
  147.   "accesskey",
  148.   "action",
  149.   "align",
  150.   "alt",
  151.   "axes",
  152.   "axis",
  153.   "char",
  154.   "charset",
  155.   "cite",
  156.   "class",
  157.   "classid",
  158.   "code",
  159.   "color",
  160.   "datetime",
  161.   "dir",
  162.   "enctype",
  163.   "face",
  164.   "height",
  165.   "id",
  166.   "lang",
  167.   "language",
  168.   "media",
  169.   "method",
  170.   "name",
  171.   "prompt",
  172.   "scheme",
  173.   "size",
  174.   "style",
  175.   "target",
  176.   "title",
  177.   "type",
  178.   "valign",
  179.   "version",
  180.   "width",
  181.   ""
  182. };
  183.  
  184.  
  185. /* dΘtection de mini-code javascript */
  186. /* ALSO USED: detection based on the name: onXXX="<tag>" where XXX starts with upper case letter */
  187. const char* hts_detect_js[] = {
  188.   "onAbort",
  189.   "onBlur",
  190.   "onChange",
  191.   "onClick",
  192.   "onDblClick",
  193.   "onDragDrop",
  194.   "onError",
  195.   "onFocus",
  196.   "onKeyDown",
  197.   "onKeyPress",
  198.   "onKeyUp",
  199.   "onLoad",
  200.   "onMouseDown",
  201.   "onMouseMove",
  202.   "onMouseOut",
  203.   "onMouseOver",
  204.   "onMouseUp",
  205.   "onMove",
  206.   "onReset",
  207.   "onResize",
  208.   "onSelect",
  209.   "onSubmit",
  210.   "onUnload",
  211.   "style",          /* hack for CSS code data */
  212.   ""
  213. };
  214.  
  215. const char* hts_main_mime[] = {
  216.   "application",
  217.   "audio",
  218.   "image",
  219.   "message",
  220.   "multipart",
  221.   "text",
  222.   "video",
  223.   ""
  224. };
  225.  
  226. /* dΘtection "...URL=<url>" */
  227. const char* hts_detectURL[] = {
  228.   "content",
  229.   ""
  230. };
  231.  
  232. /* tags o∙ l'URL doit Ωtre rΘΘcrite mais non capturΘe */
  233. const char* hts_detectandleave[] = {
  234.   "action",
  235.   ""
  236. };
  237.  
  238. /* ne pas renommer les types renvoyΘs (souvent types inconnus) */
  239. const char* hts_mime_keep[] = {
  240.   "application/octet-stream",
  241.   "text/plain",
  242.   ""
  243. };
  244.  
  245. /* pas de type mime connu, mais extension connue */
  246. const char* hts_ext_dynamic[] = {
  247.   "php3",
  248.   "php",
  249.   "php4",
  250.   "php2",
  251.   "cgi",
  252.   "asp",
  253.   "jsp",
  254.   "pl",
  255.   /*"exe",*/
  256.   "cfm",
  257.   "nsf", /* lotus */
  258.   ""
  259. };
  260.  
  261. /* types MIME 
  262.    note: application/octet-stream should not be used here
  263. */
  264. const char* hts_mime[][2] = {
  265.   {"application/acad","dwg"},
  266.   {"application/arj","arj"},
  267.   {"application/clariscad","ccad"},
  268.   {"application/drafting","drw"},
  269.   {"application/dxf","dxf"},
  270.   {"application/excel","xls"},
  271.   {"application/i-deas","unv"},
  272.   {"application/iges","isg"},
  273.   {"application/iges","iges"},
  274.   {"application/mac-binhex40","hqx"},
  275.   {"application/mac-compactpro","cpt"},
  276.   {"application/msword","doc"},
  277.   {"application/msword","w6w"},
  278.   {"application/msword","word"},
  279.   {"application/mswrite","wri"},
  280.   /*{"application/octet-stream","dms"},*/
  281.   /*{"application/octet-stream","lzh"},*/
  282.   /*{"application/octet-stream","lha"},*/
  283.   /*{"application/octet-stream","bin"},*/
  284.   {"application/oda","oda"},
  285.   {"application/pdf","pdf"},
  286.   {"application/postscript","ps"},
  287.   {"application/postscript","ai"},
  288.   {"application/postscript","eps"},
  289.   {"application/powerpoint","ppt"},
  290.   {"application/pro_eng","prt"},
  291.   {"application/pro_eng","part"},
  292.   {"application/rtf","rtf"},
  293.   {"application/set","set"},
  294.   {"application/sla","stl"},
  295.   {"application/smil","smi"},
  296.   {"application/smil","smil"},
  297.   {"application/smil","sml"},
  298.   {"application/solids","sol"},
  299.   {"application/STEP","stp"},
  300.   {"application/STEP","step"},
  301.   {"application/vda","vda"},
  302.   {"application/x-authorware-map","aam"},     
  303.   {"application/x-authorware-seg","aas"},
  304.   {"application/x-authorware-bin","aab"},
  305.   {"application/x-bzip2","bz2"},
  306.   {"application/x-cocoa","cco"},
  307.   {"application/x-csh","csh"},
  308.   {"application/x-director","dir"},
  309.   {"application/x-director","dcr"},
  310.   {"application/x-director","dxr"},
  311.   {"application/x-mif","mif"},
  312.   {"application/x-dvi","dvi"},
  313.   {"application/x-gzip","gz"},
  314.   {"application/x-gzip","gzip"},
  315.   {"application/x-hdf","hdf"},
  316.   {"application/x-javascript","js"},
  317.   {"application/x-koan","skp"},
  318.   {"application/x-koan","skd"},
  319.   {"application/x-koan","skt"},
  320.   {"application/x-koan","skm"},
  321.   {"application/x-latex","latex"},
  322.   {"application/x-netcdf","nc"},
  323.   {"application/x-netcdf","cdf"},
  324.   /* {"application/x-sh","sh"}, */
  325.   /* {"application/x-csh","csh"}, */
  326.   /* {"application/x-ksh","ksh"}, */
  327.   {"application/x-shar","shar"},
  328.   {"application/x-stuffit","sit"},
  329.   {"application/x-tcl","tcl"},
  330.   {"application/x-tex","tex"},
  331.   {"application/x-texinfo","texinfo"},
  332.   {"application/x-texinfo","texi"},
  333.   {"application/x-troff","t"},
  334.   {"application/x-troff","tr"},
  335.   {"application/x-troff","roff"},
  336.   {"application/x-troff-man","man"},
  337.   {"application/x-troff-me","ms"},
  338.   {"application/x-wais-source","src"},
  339.   {"application/zip","zip"},
  340.   {"application/x-zip-compressed","zip"},
  341.   {"application/x-bcpio","bcpio"},
  342.   {"application/x-cdlink","vcd"},
  343.   {"application/x-cpio","cpio"},
  344.   {"application/x-gtar","tgz"},
  345.   {"application/x-gtar","gtar"},
  346.   {"application/x-shar","shar"},
  347.   {"application/x-shockwave-flash","swf"},
  348.   {"application/x-sv4cpio","sv4cpio"},
  349.   {"application/x-sv4crc","sv4crc"},
  350.   {"application/x-tar","tar"},
  351.   {"application/x-ustar","ustar"},
  352.   {"application/x-winhelp","hlp"},
  353.   {"application/xml","xml"},  
  354.   {"audio/midi","mid"},
  355.   {"audio/midi","midi"},
  356.   {"audio/midi","kar"},
  357.   {"audio/mpeg","mp3"},
  358.   {"audio/mpeg","mpga"},
  359.   {"audio/mpeg","mp2"},
  360.   {"audio/basic","au"},
  361.   {"audio/basic","snd"},
  362.   {"audio/x-aiff","aif"},
  363.   {"audio/x-aiff","aiff"},
  364.   {"audio/x-aiff","aifc"},
  365.   {"audio/x-pn-realaudio","rm"},
  366.   {"audio/x-pn-realaudio","ram"},
  367.   {"audio/x-pn-realaudio","ra"},
  368.   {"audio/x-pn-realaudio-plugin","rpm"},
  369.   {"audio/x-wav","wav"},
  370.   {"chemical/x-pdb","pdb"},
  371.   {"chemical/x-pdb","xyz"},
  372.   {"drawing/x-dwf","dwf"},
  373.   {"image/gif","gif"},
  374.   {"image/ief","ief"},
  375.   {"image/jpeg","jpg"},
  376.   {"image/jpeg","jpe"},
  377.   {"image/jpeg","jpeg"},
  378.   {"image/pict","pict"},
  379.   {"image/png","png"},
  380.   {"image/tiff","tiff"},
  381.   {"image/tiff","tif"},
  382.   {"image/svg+xml","svg"},
  383.   {"image/svg-xml","svg"},
  384.   {"image/x-cmu-raster","ras"},
  385.   {"image/x-freehand","fh4"},
  386.   {"image/x-freehand","fh7"},
  387.   {"image/x-freehand","fh5"},  
  388.   {"image/x-freehand","fhc"},
  389.   {"image/x-freehand","fh"},   
  390.   {"image/x-portable-anymap","pnm"},
  391.   {"image/x-portable-bitmap","pgm"},
  392.   {"image/x-portable-pixmap","ppm"},
  393.   {"image/x-rgb","rgb"},
  394.   {"image/x-xbitmap","xbm"},
  395.   {"image/x-xpixmap","xpm"},
  396.   {"image/x-xwindowdump","xwd"},
  397.   {"model/mesh","msh"},  
  398.   {"model/mesh","mesh"},  
  399.   {"model/mesh","silo"},  
  400.   {"multipart/x-zip","zip"},
  401.   {"multipart/x-gzip","gzip"},
  402.   {"text/css","css"},
  403.   {"text/html","html"},
  404.   {"text/html","htm"},
  405.   {"text/plain","txt"},
  406.   {"text/plain","g"},
  407.   {"text/plain","h"},
  408.   {"text/plain","c"},
  409.   {"text/plain","cc"},
  410.   {"text/plain","hh"},
  411.   {"text/plain","m"},
  412.   {"text/plain","f90"},
  413.   {"text/richtext","rtx"},
  414.   {"text/tab-separated-values","tsv"},
  415.   {"text/x-setext","etx"},
  416.   {"text/x-sgml","sgml"},
  417.   {"text/x-sgml","sgm"},
  418.   {"text/xml","xml"},  
  419.   {"text/xml","dtd"},  
  420.   {"video/mpeg","mpeg"},
  421.   {"video/mpeg","mpg"},
  422.   {"video/mpeg","mpe"},
  423.   {"video/quicktime","qt"},
  424.   {"video/quicktime","mov"},
  425.   {"video/x-msvideo","avi"},
  426.   {"video/x-sgi-movie","movie"},
  427.   {"x-conference/x-cooltalk","ice"},
  428.   /*{"application/x-httpd-cgi","cgi"},*/
  429.   {"x-world/x-vrml","wrl"},
  430.  
  431.   /* More from w3schools.com */
  432.   { "application/envoy", "evy" },
  433.   { "application/fractals", "fif" },
  434.   { "application/futuresplash", "spl" },
  435.   { "application/hta", "hta" },
  436.   { "application/internet-property-stream", "acx" },
  437.   { "application/msword", "dot" },
  438.   { "application/olescript", "axs" },
  439.   { "application/pics-rules", "prf" },
  440.   { "application/pkcs10", "p10" },
  441.   { "application/pkix-crl", "crl" },
  442.   { "application/set-payment-initiation", "setpay" },
  443.   { "application/set-registration-initiation", "setreg" },
  444.   { "application/vnd.ms-excel", "xls" },
  445.   { "application/vnd.ms-excel", "xla" },
  446.   { "application/vnd.ms-excel", "xlc" },
  447.   { "application/vnd.ms-excel", "xlm" },
  448.   { "application/vnd.ms-excel", "xlt" },
  449.   { "application/vnd.ms-excel", "xlw" },
  450.   { "application/vnd.ms-pkicertstore", "sst" },
  451.   { "application/vnd.ms-pkiseccat", "cat" },
  452.   { "application/vnd.ms-powerpoint", "ppt" },
  453.   { "application/vnd.ms-powerpoint", "pot" },
  454.   { "application/vnd.ms-powerpoint", "pps" },
  455.   { "application/vnd.ms-project", "mpp" },
  456.   { "application/vnd.ms-works", "wcm" },
  457.   { "application/vnd.ms-works", "wdb" },
  458.   { "application/vnd.ms-works", "wks" },
  459.   { "application/vnd.ms-works", "wps" },
  460.   { "application/x-compress", "z" },
  461.   { "application/x-compressed", "tgz" },
  462.   { "application/x-internet-signup", "ins" },
  463.   { "application/x-internet-signup", "isp" },
  464.   { "application/x-iphone", "iii" },
  465.   { "application/x-javascript", "js" },
  466.   { "application/x-msaccess", "mdb" },
  467.   { "application/x-mscardfile", "crd" },
  468.   { "application/x-msclip", "clp" },
  469.   { "application/x-msmediaview", "m13" },
  470.   { "application/x-msmediaview", "m14" },
  471.   { "application/x-msmediaview", "mvb" },
  472.   { "application/x-msmetafile", "wmf" },
  473.   { "application/x-msmoney", "mny" },
  474.   { "application/x-mspublisher", "pub" },
  475.   { "application/x-msschedule", "scd" },
  476.   { "application/x-msterminal", "trm" },
  477.   { "application/x-perfmon", "pma" },
  478.   { "application/x-perfmon", "pmc" },
  479.   { "application/x-perfmon", "pml" },
  480.   { "application/x-perfmon", "pmr" },
  481.   { "application/x-perfmon", "pmw" },
  482.   { "application/x-pkcs12", "p12" },
  483.   { "application/x-pkcs12", "pfx" },
  484.   { "application/x-pkcs7-certificates", "p7b" },
  485.   { "application/x-pkcs7-certificates", "spc" },
  486.   { "application/x-pkcs7-certreqresp", "p7r" },
  487.   { "application/x-pkcs7-mime", "p7c" },
  488.   { "application/x-pkcs7-mime", "p7m" },
  489.   { "application/x-pkcs7-signature", "p7s" },
  490.   { "application/x-troff-me", "me" },
  491.   { "application/x-x509-ca-cert", "cer" },
  492.   { "application/x-x509-ca-cert", "crt" },
  493.   { "application/x-x509-ca-cert", "der" },
  494.   { "application/ynd.ms-pkipko", "pko" },
  495.   { "audio/mid", "mid" },
  496.   { "audio/mid", "rmi" },
  497.   { "audio/mpeg", "mp3" },
  498.   { "audio/x-mpegurl", "m3u" },
  499.   { "image/bmp", "bmp" },
  500.   { "image/cis-cod", "cod" },
  501.   { "image/pipeg", "jfif" },
  502.   { "image/x-cmx", "cmx" },
  503.   { "image/x-icon", "ico" },
  504.   { "image/x-portable-bitmap", "pbm" },
  505.   { "message/rfc822", "mht" },
  506.   { "message/rfc822", "mhtml" },
  507.   { "message/rfc822", "nws" },
  508.   { "text/css", "css" },
  509.   { "text/h323", "323" },
  510.   { "text/html", "stm" },
  511.   { "text/iuls", "uls" },
  512.   { "text/plain", "bas" },
  513.   { "text/scriptlet", "sct" },
  514.   { "text/webviewhtml", "htt" },
  515.   { "text/x-component", "htc" },
  516.   { "text/x-vcard", "vcf" },
  517.   { "video/mpeg", "mp2" },
  518.   { "video/mpeg", "mpa" },
  519.   { "video/mpeg", "mpv2" },
  520.   { "video/x-la-asf", "lsf" },
  521.   { "video/x-la-asf", "lsx" },
  522.   { "video/x-ms-asf", "asf" },
  523.   { "video/x-ms-asf", "asr" },
  524.   { "video/x-ms-asf", "asx" },
  525.   { "video/x-ms-wmv", "wmv" },
  526.   { "x-world/x-vrml", "flr" },
  527.   { "x-world/x-vrml", "vrml" },
  528.   { "x-world/x-vrml", "wrz" },
  529.   { "x-world/x-vrml", "xaf" },
  530.   { "x-world/x-vrml", "xof" },
  531.  
  532.   /* Various */
  533.   { "application/ogg", "ogg" },
  534.  
  535.   {"application/x-java-vm","class"},
  536.   
  537.   {"",""}};
  538.  
  539.  
  540. // Reserved (RFC2396)
  541. #define CIS(c,ch) ( ((unsigned char)(c)) == (ch) )
  542. #define CHAR_RESERVED(c)  ( CIS(c,';') \
  543.                          || CIS(c,'/') \
  544.                          || CIS(c,'?') \
  545.                          || CIS(c,':') \
  546.                          || CIS(c,'@') \
  547.                          || CIS(c,'&') \
  548.                          || CIS(c,'=') \
  549.                          || CIS(c,'+') \
  550.                          || CIS(c,'$') \
  551.                          || CIS(c,',') )
  552. //#define CHAR_RESERVED(c)  ( strchr(";/?:@&=+$,",(unsigned char)(c)) != 0 )
  553. // Delimiters (RFC2396)
  554. #define CHAR_DELIM(c)     ( CIS(c,'<') \
  555.                          || CIS(c,'>') \
  556.                          || CIS(c,'#') \
  557.                          || CIS(c,'%') \
  558.                          || CIS(c,'\"') )
  559. //#define CHAR_DELIM(c)     ( strchr("<>#%\"",(unsigned char)(c)) != 0 )
  560. // Unwise (RFC2396)
  561. #define CHAR_UNWISE(c)    ( CIS(c,'{') \
  562.                          || CIS(c,'}') \
  563.                          || CIS(c,'|') \
  564.                          || CIS(c,'\\') \
  565.                          || CIS(c,'^') \
  566.                          || CIS(c,'[') \
  567.                          || CIS(c,']') \
  568.                          || CIS(c,'`') )
  569. //#define CHAR_UNWISE(c)    ( strchr("{}|\\^[]`",(unsigned char)(c)) != 0 )
  570. // Special (escape chars) (RFC2396 + >127 )
  571. #define CHAR_LOW(c)       ( ((unsigned char)(c) <= 31) )
  572. #define CHAR_HIG(c)       ( ((unsigned char)(c) >= 127) )
  573. #define CHAR_SPECIAL(c)   ( CHAR_LOW(c) || CHAR_HIG(c) )
  574. // We try to avoid them and encode them instead
  575. #define CHAR_XXAVOID(c)   ( CIS(c,' ') \
  576.                          || CIS(c,'*') \
  577.                          || CIS(c,'\'') \
  578.                          || CIS(c,'\"') \
  579.                          || CIS(c,'&') \
  580.                          || CIS(c,'!') )
  581. //#define CHAR_XXAVOID(c)   ( strchr(" *'\"!",(unsigned char)(c)) != 0 )
  582. #define CHAR_MARK(c)      ( CIS(c,'-') \
  583.                          || CIS(c,'_') \
  584.                          || CIS(c,'.') \
  585.                          || CIS(c,'!') \
  586.                          || CIS(c,'~') \
  587.                          || CIS(c,'*') \
  588.                          || CIS(c,'\'') \
  589.                          || CIS(c,'(') \
  590.                          || CIS(c,')') )
  591. //#define CHAR_MARK(c)      ( strchr("-_.!~*'()",(unsigned char)(c)) != 0 )
  592.  
  593.  
  594.  
  595. // conversion Θventuelle / vers antislash
  596. #ifdef _WIN32
  597. char* antislash(char *catbuff, const char* s) {
  598.   char* a;
  599.   strcpybuff(catbuff,s);
  600.   while(a=strchr(catbuff,'/')) *a='\\';
  601.   return catbuff;
  602. }
  603. #endif
  604.  
  605. #ifdef _WIN32_WCE
  606. char cwd[MAX_PATH+1] = "";
  607. #endif
  608.  
  609. // RΘcupΘration d'un fichier http sur le net.
  610. // Renvoie une adresse sur le bloc de mΘmoire, ou bien
  611. // NULL si un retour.msgeur (buffer retour.msg) est survenue. 
  612. //
  613. // Une adresse de structure htsmsg peut Ωtre transmise pour
  614. // suivre l'Θvolution du chargement si le process a ΘtΘ lancΘ 
  615. // en background
  616.  
  617. htsblk httpget(httrackp *opt,char* url) {
  618.   char BIGSTK adr[HTS_URLMAXSIZE*2];   // adresse
  619.   char BIGSTK fil[HTS_URLMAXSIZE*2];   // chemin
  620.   
  621.   // sΘparer URL en adresse+chemin
  622.   if (ident_url_absolute(url,adr,fil)==-1) {
  623.     htsblk retour;
  624.     memset(&retour, 0, sizeof(htsblk));    // effacer
  625.     // retour prΘdΘfini: erreur
  626.     retour.adr=NULL;
  627.     retour.size=0;
  628.     retour.msg[0]='\0';
  629.     retour.statuscode=STATUSCODE_INVALID;    
  630.     strcpybuff(retour.msg,"Error invalid URL");
  631.     return retour;
  632.   }
  633.   
  634.   return xhttpget(opt,adr,fil);
  635. }
  636.  
  637. // ouvre une liaison http, envoie une requΦte GET et rΘceptionne le header
  638. // retour: socket
  639. int http_fopen(httrackp *opt,char* adr,char* fil,htsblk* retour) {
  640.   //                / GET, traiter en-tΩte
  641.   return http_xfopen(opt,0,1,1,NULL,adr,fil,retour);
  642. }
  643.  
  644. // ouverture d'une liaison http, envoi d'une requΦte
  645. // mode: 0 GET  1 HEAD  [2 POST]
  646. // treat: traiter header?
  647. // waitconnect: attendre le connect()
  648. // note: dans retour, on met les params du proxy
  649. int http_xfopen(httrackp *opt,int mode,int treat,int waitconnect,char* xsend,char* adr,char* fil,htsblk* retour) {
  650.   //htsblk retour;
  651.   //int bufl=TAILLE_BUFFER;    // 8Ko de buffer
  652.   T_SOC soc=INVALID_SOCKET;
  653.   //char *p,*q;
  654.   
  655.   // retour prΘdΘfini: erreur
  656.   if (retour) {
  657.     retour->adr=NULL;
  658.     retour->size=0;
  659.     retour->msg[0]='\0';
  660.     retour->statuscode=STATUSCODE_NON_FATAL;          // a priori erreur non fatale
  661.   }
  662.  
  663. #if HDEBUG
  664.   printf("adr=%s\nfichier=%s\n",adr,fil);
  665. #endif
  666.   
  667.   // ouvrir liaison
  668. #if HDEBUG
  669.   printf("CrΘation d'une socket sur %s\n",adr);
  670. #endif
  671.  
  672. #if CNXDEBUG
  673.   printf("..newhttp\n");
  674. #endif
  675.  
  676.   /* connexion */
  677.   if (retour) {
  678.     if ( (!(retour->req.proxy.active)) 
  679.       ||
  680.       (
  681.         (strcmp(adr,"file://")==0) 
  682.         ||
  683.         (strncmp(adr,"https://", 8)==0) 
  684.       )
  685.       ) {    /* pas de proxy, ou non utilisable ici */
  686.       soc=newhttp(opt,adr,retour,-1,waitconnect);
  687.     } else {
  688.       soc=newhttp(opt, retour->req.proxy.name, retour,retour->req.proxy.port, waitconnect);  // ouvrir sur le proxy α la place
  689.     }
  690.   } else {
  691.     soc=newhttp(opt,adr,NULL,-1,waitconnect);    
  692.   }
  693.  
  694.   // copier index socket retour
  695.   if (retour) retour->soc=soc;
  696.  
  697.   /* Check for errors */
  698.   if (soc == INVALID_SOCKET) {
  699.     if (retour) {
  700.       if (retour->msg) {
  701.         if (!strnotempty(retour->msg)) {
  702. #ifdef _WIN32
  703.           int last_errno = WSAGetLastError();
  704.           sprintf(retour->msg,"Connect error: %s", strerror(last_errno));
  705. #else
  706.           int last_errno = errno;
  707.           sprintf(retour->msg,"Connect error: %s", strerror(last_errno));
  708. #endif
  709.         }
  710.       }
  711.     }
  712.   }
  713.  
  714.   // --------------------
  715.   // court-circuit (court circuite aussi le proxy..)
  716.   // LOCAL_SOCKET_ID est une pseudo-socket locale
  717.   if (soc==LOCAL_SOCKET_ID) {
  718.     retour->is_file=1;  // fichier local
  719.     if (mode==0) {    // GET
  720.  
  721.       // Test en cas de file:///C|...
  722.       if (!fexist(fconv(OPT_GET_BUFF(opt), unescape_http(OPT_GET_BUFF(opt),fil))))
  723.         if (fexist(fconv(OPT_GET_BUFF(opt), unescape_http(OPT_GET_BUFF(opt),fil+1)))) {
  724.           char BIGSTK tempo[HTS_URLMAXSIZE*2];
  725.           strcpybuff(tempo,fil+1);
  726.           strcpybuff(fil,tempo);
  727.         }
  728.  
  729.       // Ouvrir
  730.       retour->totalsize=fsize(fconv(OPT_GET_BUFF(opt), unescape_http(OPT_GET_BUFF(opt),fil)));  // taille du fichier
  731.       retour->msg[0]='\0';
  732.       soc=INVALID_SOCKET;
  733.       if (retour->totalsize<0)
  734.         strcpybuff(retour->msg,"Unable to open local file");
  735.       else if (retour->totalsize==0)
  736.         strcpybuff(retour->msg,"File empty");
  737.       else {
  738.         // Note: On passe par un FILE* (plus propre)
  739.         //soc=open(fil,O_RDONLY,0);    // en lecture seule!
  740.         retour->fp=fopen(fconv(OPT_GET_BUFF(opt), unescape_http(OPT_GET_BUFF(opt),fil)),"rb");  // ouvrir
  741.         if (retour->fp==NULL)
  742.           soc=INVALID_SOCKET;
  743.         else
  744.           soc=LOCAL_SOCKET_ID;
  745.       }
  746.       retour->soc=soc;
  747.       if (soc!=INVALID_SOCKET) {
  748.         retour->statuscode=HTTP_OK;   // OK
  749.         strcpybuff(retour->msg,"OK");
  750.         guess_httptype(opt,retour->contenttype,fil);
  751.       } else if (strnotempty(retour->msg)==0)
  752.           strcpybuff(retour->msg,"Unable to open local file");
  753.       return soc;  // renvoyer
  754.     } else {    // HEAD ou POST : interdit sur un local!!!! (c'est idiot!)
  755.       strcpybuff(retour->msg,"Unexpected Head/Post local request");
  756.       soc=INVALID_SOCKET;    // erreur
  757.       retour->soc=soc;
  758.       return soc;
  759.     }
  760.   } 
  761.   // --------------------
  762.  
  763.   if (soc!=INVALID_SOCKET) {    
  764.     char rcvd[1100];
  765.     rcvd[0]='\0';
  766. #if HDEBUG
  767.     printf("Ok, connexion rΘussie, id=%d\n",soc);
  768. #endif
  769.     
  770.     // connectΘ?
  771.     if (waitconnect) {
  772.       http_sendhead(opt,NULL,mode,xsend,adr,fil,NULL,NULL,retour);
  773.     } 
  774.     
  775.     if (soc!=INVALID_SOCKET) {
  776.       
  777. #if HDEBUG
  778.       printf("Attente de la rΘponse:\n");
  779. #endif
  780.       
  781.       // si GET (rΘception d'un fichier), rΘceptionner en-tΩte d'abord,
  782.       // et ensuite le corps
  783.       // si POST on ne rΘceptionne rien du tout, c'est aprΦs que l'on fera
  784.       // une rΘception standard pour rΘcupΘrer l'en tΩte
  785.       if ((treat) && (waitconnect)) {  // traiter (attendre!) en-tΩte        
  786.         // RΘception de la status line et de l'en-tΩte (norme RFC1945)
  787.         
  788.         // status-line α rΘcupΘrer
  789.         finput(soc,rcvd,1024);
  790.         if (strnotempty(rcvd)==0)
  791.           finput(soc,rcvd,1024);    // "certains serveurs buggΘs envoient un \n au dΘbut" (RFC)
  792.  
  793.         // traiter status-line
  794.         treatfirstline(retour,rcvd);
  795.  
  796. #if HDEBUG
  797.         printf("Status-Code=%d\n",retour->statuscode);
  798. #endif
  799.         
  800.         // en-tΩte
  801.         
  802.         // header // ** !attention! HTTP/0.9 non supportΘ
  803.         do {
  804.           finput(soc,rcvd,1024);          
  805. #if HDEBUG
  806.           printf(">%s\n",rcvd);      
  807. #endif
  808.           if (strnotempty(rcvd))
  809.             treathead(NULL,NULL,NULL,retour,rcvd);  // traiter
  810.  
  811.         } while(strnotempty(rcvd));
  812.         
  813.         //rcvsize=-1;    // forCER CHARGEMENT INCONNU
  814.         
  815.         //if (retour)
  816.         //  retour->totalsize=rcvsize;
  817.         
  818.       } else { // si GET, on recevra l'en tΩte APRES
  819.         //rcvsize=-1;    // on ne connait pas la taille de l'en-tΩte
  820.         if (retour)
  821.           retour->totalsize=-1;
  822.       }
  823.       
  824.     }
  825.  
  826.   }
  827.     
  828.   return soc;
  829. }
  830.  
  831.  
  832. // envoi d'une requΦte
  833. int http_sendhead(httrackp *opt,t_cookie* cookie,int mode,char* xsend,char* adr,char* fil,char* referer_adr,char* referer_fil,htsblk* retour) {
  834.   char BIGSTK buff[8192];
  835.   //int use_11=0;     // HTTP 1.1 utilisΘ
  836.   int direct_url=0; // ne pas analyser l'url (exemple: ftp://)
  837.   char* search_tag=NULL;
  838.   buff[0]='\0';
  839.  
  840.   // header Date
  841.   //strcatbuff(buff,"Date: ");
  842.   //time_gmt_rfc822(buff);    // obtenir l'heure au format rfc822
  843.   //sendc("\n");
  844.   //strcatbuff(buff,buff);
  845.  
  846.   // possibilitΘ non documentΘe: >post: et >postfile:
  847.   // si prΘsence d'un tag >post: alors executer un POST
  848.   // exemple: http://www.someweb.com/test.cgi?foo>post:posteddata=10&foo=5
  849.   // si prΘsence d'un tag >postfile: alors envoyer en tΩte brut contenu dans le fichier en question
  850.   // exemple: http://www.someweb.com/test.cgi?foo>postfile:post0.txt
  851.   search_tag=strstr(fil,POSTTOK":");
  852.   if (!search_tag) {
  853.     search_tag=strstr(fil,POSTTOK"file:");
  854.     if (search_tag) {     // postfile
  855.       if (mode==0) {      // GET!
  856.         FILE* fp=fopen(unescape_http(OPT_GET_BUFF(opt),search_tag+strlen(POSTTOK)+5),"rb");
  857.         if (fp) {
  858.           char BIGSTK line[1100];
  859.           char BIGSTK protocol[256],url[HTS_URLMAXSIZE*2],method[256];
  860.           linput(fp,line,1000);
  861.           if (sscanf(line,"%s %s %s",method,url,protocol) == 3) {
  862.             // selon que l'on a ou pas un proxy
  863.             if (retour->req.proxy.active)
  864.               sprintf(buff,"%s http://%s%s %s\r\n",method,adr,url,protocol);
  865.             else
  866.               sprintf(buff,"%s %s %s\r\n",method,url,protocol);
  867.             // lire le reste en brut
  868.             fread(buff+strlen(buff),8000-strlen(buff),1,fp);
  869.           }
  870.           fclose(fp);
  871.         }
  872.       }
  873.     }
  874.   }
  875.   // Fin postfile
  876.   
  877.   if (strnotempty(buff)==0) {    // PAS POSTFILE
  878.     // Type de requΦte?
  879.     if ((search_tag) && (mode==0)) {
  880.       strcatbuff(buff,"POST ");
  881.     } else if (mode==0) {    // GET
  882.       strcatbuff(buff,"GET ");
  883.     } else {  // if (mode==1) {
  884.       if (!retour->req.http11)        // forcer HTTP/1.0
  885.         strcatbuff(buff,"GET ");      // certains serveurs (cgi) buggent avec HEAD
  886.       else
  887.         strcatbuff(buff,"HEAD ");
  888.     }
  889.     
  890.     // si on gΦre un proxy, il faut une Absolute URI: on ajoute avant http://www.adr.dom
  891.     if ( retour->req.proxy.active && (strncmp(adr,"https://", 8) != 0) ) {
  892.       if (!link_has_authority(adr)) {  // default http
  893. #if HDEBUG
  894.         printf("Proxy Use: for %s%s proxy %d port %d\n",adr,fil,retour->req.proxy.name,retour->req.proxy.port);
  895. #endif
  896.         strcatbuff(buff,"http://");
  897.         strcatbuff(buff,jump_identification(adr));
  898.       } else {          // ftp:// en proxy http
  899. #if HDEBUG
  900.         printf("Proxy Use for ftp: for %s%s proxy %d port %d\n",adr,fil,retour->req.proxy.name,retour->req.proxy.port);
  901. #endif
  902.         direct_url=1;             // ne pas analyser user/pass
  903.         strcatbuff(buff,adr);
  904.       }
  905.     } 
  906.     
  907.     // NOM DU FICHIER
  908.     // on slash doit Ωtre prΘsent en dΘbut, sinon attention aux bad request! (400)
  909.     if (*fil!='/') strcatbuff(buff,"/");
  910.     {
  911.       char BIGSTK tempo[HTS_URLMAXSIZE*2];
  912.       tempo[0]='\0';
  913.       if (search_tag)
  914.         strncatbuff(tempo,fil,(int) (search_tag - fil));
  915.       else
  916.         strcpybuff(tempo,fil);
  917.       escape_check_url(tempo);
  918.       strcatbuff(buff,tempo);       // avec Θchappement
  919.     }
  920.     
  921.     // protocole
  922.     if (!retour->req.http11) {     // forcer HTTP/1.0
  923.       //use_11=0;
  924.       strcatbuff(buff," HTTP/1.0\x0d\x0a");
  925.     } else {                   // RequΦte 1.1
  926.       //use_11=1;
  927.       strcatbuff(buff," HTTP/1.1\x0d\x0a");
  928.     }
  929.  
  930.     /* supplemental data */
  931.     if (xsend) strcatbuff(buff,xsend);    // Θventuelles autres lignes
  932.  
  933.     // tester proxy authentication
  934.     if (retour->req.proxy.active) {
  935.       if (link_has_authorization(retour->req.proxy.name)) {  // et hop, authentification proxy!
  936.         const char* a = jump_identification(retour->req.proxy.name);
  937.         const char* astart = jump_protocol(retour->req.proxy.name);
  938.         char autorisation[1100];
  939.         char user_pass[256];        
  940.         autorisation[0]=user_pass[0]='\0';
  941.         //
  942.         strncatbuff(user_pass,astart,(int) (a - astart) - 1);
  943.         strcpybuff(user_pass,unescape_http(OPT_GET_BUFF(opt),user_pass));
  944.         code64((unsigned char*)user_pass,(int)strlen(user_pass),(unsigned char*)autorisation,0);
  945.         strcatbuff(buff,"Proxy-Authorization: Basic ");
  946.         strcatbuff(buff,autorisation);
  947.         strcatbuff(buff,H_CRLF);
  948. #if HDEBUG
  949.         printf("Proxy-Authenticate, %s (code: %s)\n",user_pass,autorisation);
  950. #endif
  951.       }
  952.     }
  953.     
  954.     // Referer?
  955.     if (referer_adr != NULL && referer_fil != NULL 
  956.       && strnotempty(referer_adr) && strnotempty(referer_fil)
  957.       ) {   // non vide
  958.       if (
  959.         (strcmp(referer_adr,"file://") != 0)
  960.         &&
  961.         (  /* no https referer to http urls */
  962.         (strncmp(referer_adr, "https://", 8) != 0)  /* referer is not https */
  963.         ||
  964.         (strncmp(adr, "https://", 8) == 0)          /* or referer AND addresses are https */
  965.         )
  966.         ) {      // PAS file://
  967.         strcatbuff(buff,"Referer: ");
  968.         strcatbuff(buff,"http://");
  969.         strcatbuff(buff,jump_identification(referer_adr));
  970.         strcatbuff(buff,referer_fil);
  971.         strcatbuff(buff,H_CRLF);
  972.       }
  973.     }
  974.     // HTTP field: referer
  975.     else if (retour->req.referer[0] != '\0') {
  976.       strcatbuff(buff,"Referer: ");
  977.       strcatbuff(buff, retour->req.referer);
  978.       strcatbuff(buff, H_CRLF);     
  979.     }
  980.     
  981.     // POST?
  982.     if (mode==0) {      // GET!
  983.       if (search_tag) {
  984.         char clen[256];
  985.         sprintf(clen,"Content-length: %d"H_CRLF,(int)(strlen(unescape_http(OPT_GET_BUFF(opt),search_tag+strlen(POSTTOK)+1))));
  986.         strcatbuff(buff,clen);
  987.       }
  988.     }
  989.     
  990.     // gestion cookies?
  991.     if (cookie) {
  992.             char buffer[8192];
  993.       char* b=cookie->data;
  994.       int cook=0;
  995.       int max_cookies=8;
  996.       size_t max_size=2048;
  997.       max_size+=strlen(buff);
  998.       do {
  999.         b=cookie_find(b,"",jump_identification(adr),fil);       // prochain cookie satisfaisant aux conditions
  1000.         if (b) {
  1001.           max_cookies--;
  1002.           if (!cook) {
  1003.             strcatbuff(buff,"Cookie: ");
  1004.             strcatbuff(buff,"$Version=1; ");
  1005.             cook=1;
  1006.           } else
  1007.             strcatbuff(buff,"; ");
  1008.           strcatbuff(buff,cookie_get(buffer,b,5));
  1009.           strcatbuff(buff,"=");
  1010.           strcatbuff(buff,cookie_get(buffer,b,6));
  1011.           strcatbuff(buff,"; $Path=");
  1012.           strcatbuff(buff,cookie_get(buffer,b,2));
  1013.           b=cookie_nextfield(b);
  1014.         }
  1015.       } while( (b) && (max_cookies>0) && ((int)strlen(buff)<max_size));
  1016.       if (cook) {                           // on a envoyΘ un (ou plusieurs) cookie?
  1017.         strcatbuff(buff,H_CRLF);
  1018. #if DEBUG_COOK
  1019.         printf("Header:\n%s\n",buff);
  1020. #endif
  1021.       }
  1022.     }
  1023.     
  1024.     // gΘrer le keep-alive (garder socket)
  1025.     if (retour->req.http11 && !retour->req.nokeepalive) {
  1026.             strcatbuff(buff,"Connection: Keep-Alive"H_CRLF);
  1027.         } else {
  1028.       strcatbuff(buff,"Connection: close"H_CRLF);
  1029.         }
  1030.     
  1031.     {
  1032.       char* real_adr=jump_identification(adr);
  1033.       //if ((use_11) || (retour->user_agent_send)) {   // Pour le 1.1 on utilise un Host:
  1034.       if (!direct_url) {     // pas ftp:// par exemple
  1035.         //if (!retour->req.proxy.active) {
  1036.         strcatbuff(buff,"Host: "); strcatbuff(buff,real_adr); strcatbuff(buff,H_CRLF);
  1037.         //}
  1038.       }
  1039.       //}
  1040.  
  1041.       // HTTP field: from
  1042.       if (retour->req.from[0] != '\0') {  // HTTP from
  1043.         strcatbuff(buff,"From: ");
  1044.         strcatbuff(buff, retour->req.from);
  1045.         strcatbuff(buff, H_CRLF);
  1046.       }
  1047.  
  1048.       // PrΘsence d'un user-agent?
  1049.       if (retour->req.user_agent_send) {  // ohh un user-agent
  1050.         char s[256];
  1051.         // HyperTextSeeker/"HTSVERSION
  1052.         sprintf(s,"User-Agent: %s"H_CRLF,retour->req.user_agent);
  1053.         strcatbuff(buff,s);
  1054.         
  1055.         // pour les serveurs difficiles
  1056.         strcatbuff(buff,"Accept: "
  1057.                         "image/png, image/jpeg, image/pjpeg, image/x-xbitmap, image/svg+xml"  /* Accepted */
  1058.                         ", "
  1059.                         "image/gif;q=0.9"  /* also accepted but with lower preference */
  1060.                         ", "
  1061.                         "*/*;q=0.1"        /* also accepted but with even lower preference */
  1062.                         H_CRLF);
  1063.         if (strnotempty(retour->req.lang_iso)) {
  1064.           strcatbuff(buff,"Accept-Language: "); strcatbuff(buff,retour->req.lang_iso); strcatbuff(buff,H_CRLF);
  1065.         }
  1066.         strcatbuff(buff,"Accept-Charset: "
  1067.                         "iso-8859-1"       /* we prefer ISO-8859-1 */
  1068.                         ", "
  1069.                         "iso-8859-*;q=0.9" /* or ISO-8859-* */
  1070.                         ", "
  1071.                         "utf-8;q=0.66"     /* UTF8 is also accepted */
  1072.                         ", "
  1073.                         "*;q=0.33"         /* and any other charset */
  1074.                         H_CRLF);   
  1075.         if (retour->req.http11) {
  1076. #if HTS_USEZLIB
  1077.           //strcatbuff(buff,"Accept-Encoding: gzip, deflate, compress, identity"H_CRLF);
  1078.           if (gz_is_available && (!retour->req.range_used) && (!retour->req.nocompression))
  1079.             strcatbuff(buff,"Accept-Encoding: "
  1080.                             "gzip"         /* gzip if the preffered encoding */
  1081.                             ", "
  1082.                             "identity;q=0.9"
  1083.                             H_CRLF);
  1084.           else
  1085.             strcatbuff(buff,"Accept-Encoding: identity"H_CRLF);       /* no compression */
  1086. #else
  1087.           strcatbuff(buff,"Accept-Encoding: identity"H_CRLF);         /* no compression */
  1088. #endif
  1089.         }
  1090.       } else {
  1091.         strcatbuff(buff,"Accept: */*"H_CRLF);         // le minimum
  1092.       }
  1093.  
  1094.       /* Authentification */
  1095.       {
  1096.         char autorisation[1100];
  1097.         char* a;
  1098.         autorisation[0]='\0';
  1099.         if (link_has_authorization(adr)) {  // ohh une authentification!
  1100.           char* a=jump_identification(adr);
  1101.           char* astart=jump_protocol(adr);
  1102.           if (!direct_url) {      // pas ftp:// par exemple
  1103.             char user_pass[256];
  1104.             user_pass[0]='\0';
  1105.             strncatbuff(user_pass,astart,(int) (a - astart) - 1);
  1106.             strcpybuff(user_pass,unescape_http(OPT_GET_BUFF(opt),user_pass));
  1107.             code64((unsigned char*)user_pass,(int)strlen(user_pass),(unsigned char*)autorisation,0);
  1108.             if (strcmp(fil,"/robots.txt"))      /* pas robots.txt */
  1109.               bauth_add(cookie,astart,fil,autorisation);
  1110.           }
  1111.         } else if ( (a=bauth_check(cookie,real_adr,fil)) )
  1112.           strcpybuff(autorisation,a);
  1113.         /* On a une autorisation a donner?  */
  1114.         if (strnotempty(autorisation)) {
  1115.           strcatbuff(buff,"Authorization: Basic ");
  1116.           strcatbuff(buff,autorisation);
  1117.           strcatbuff(buff,H_CRLF);
  1118.         }
  1119.       }
  1120.  
  1121.     }
  1122.     //strcatbuff(buff,"Accept-Language: en\n");
  1123.     //strcatbuff(buff,"Accept-Charset: iso-8859-1,*,utf-8\n");
  1124.     
  1125.     // CRLF de fin d'en tΩte
  1126.     strcatbuff(buff,H_CRLF);
  1127.     
  1128.     // donnΘes complΘmentaires?
  1129.     if (search_tag)
  1130.     if (mode==0)      // GET!
  1131.       strcatbuff(buff,unescape_http(OPT_GET_BUFF(opt),search_tag+strlen(POSTTOK)+1));
  1132.   }
  1133.   
  1134. #if HDEBUG
  1135. #endif
  1136.   if (_DEBUG_HEAD) {
  1137.     if (ioinfo) {
  1138.       fprintf(ioinfo,"[%d] request for %s%s:\r\n",retour->debugid,jump_identification(adr),fil);
  1139.       fprintfio(ioinfo,buff,"<<< ");
  1140.       fprintf(ioinfo,"\r\n");
  1141.       fflush(ioinfo);
  1142.     }
  1143.   }  // Fin test pas postfile
  1144.   //
  1145.  
  1146.   // Callback
  1147.   {
  1148.     int test_head = RUN_CALLBACK6(opt, sendhead, buff, adr, fil, referer_adr, referer_fil, retour);
  1149.     if (test_head!=1) {
  1150.       deletesoc_r(retour);
  1151.       strcpybuff(retour->msg,"Header refused by external wrapper");
  1152.       retour->soc=INVALID_SOCKET;
  1153.     }
  1154.   }
  1155.  
  1156.   // Envoi
  1157.   HTS_STAT.last_request = mtime_local();
  1158.   if (sendc(retour, buff)<0) {  // ERREUR, socket rompue?...
  1159.   //if (sendc(retour->soc,buff) != strlen(buff)) {  // ERREUR, socket rompue?...
  1160.     deletesoc_r(retour);  // fermer tout de mΩme
  1161.     // et tenter de reconnecter
  1162.     
  1163.     strcpybuff(retour->msg, "Write error");
  1164.     retour->soc=INVALID_SOCKET;
  1165.   }
  1166.   
  1167.   // RX'98
  1168.   return 0;
  1169. }
  1170.  
  1171.  
  1172.  
  1173.  
  1174. // traiter 1ere ligne d'en tΩte
  1175. void treatfirstline(htsblk* retour,char* rcvd) {
  1176.   char* a=rcvd;
  1177.   // exemple:
  1178.   // HTTP/1.0 200 OK
  1179.   if (*a) {
  1180.     // note: certains serveurs buggΘs renvoient HTTP/1.0\n200 OK ou " HTTP/1.0 200 OK"
  1181.     while ((*a==' ') || (*a==10) || (*a==13) || (*a==9)) a++;      // Θpurer espaces au dΘbut
  1182.     if (strfield(a, "HTTP/")) {
  1183.       // sauter HTTP/1.x
  1184.       while ((*a!=' ') && (*a!='\0') && (*a!=10) && (*a!=13) && (*a!=9)) a++;   
  1185.       if (*a != '\0') {
  1186.         while ((*a==' ') || (*a==10) || (*a==13) || (*a==9)) a++;      // Θpurer espaces
  1187.         if ((*a>='0') && (*a<='9')) {
  1188.           sscanf(a,"%d",&(retour->statuscode));
  1189.           // sauter 200
  1190.           while ((*a!=' ') && (*a!='\0') && (*a!=10) && (*a!=13) && (*a!=9)) a++;   
  1191.           while ((*a==' ') || (*a==10) || (*a==13) || (*a==9)) a++;      // Θpurer espaces
  1192.           if ((strlen(a) > 1) && (strlen(a) < 64) )                // message retour
  1193.             strcpybuff(retour->msg,a);
  1194.           else
  1195.             infostatuscode(retour->msg,retour->statuscode);
  1196.           // type MIME par dΘfaut2
  1197.           strcpybuff(retour->contenttype,HTS_HYPERTEXT_DEFAULT_MIME);
  1198.         } else {  // pas de code!
  1199.           retour->statuscode=STATUSCODE_INVALID;
  1200.           strcpybuff(retour->msg,"Unknown response structure");
  1201.         }
  1202.       } else {  // euhh??
  1203.         retour->statuscode=STATUSCODE_INVALID;
  1204.         strcpybuff(retour->msg,"Unknown response structure");
  1205.       }
  1206.     } else {
  1207.             if (*a == '<') {
  1208.         /* This is dirty .. */
  1209.         retour->statuscode=HTTP_OK;
  1210.         retour->keep_alive=0;
  1211.         strcpybuff(retour->msg, "Unknown, assuming junky server");
  1212.         strcpybuff(retour->contenttype,HTS_HYPERTEXT_DEFAULT_MIME);
  1213.             } else if (strnotempty(a)) {
  1214.         retour->statuscode=STATUSCODE_INVALID;
  1215.         strcpybuff(retour->msg,"Unknown (not HTTP/xx) response structure");
  1216.       } else {
  1217.         /* This is dirty .. */
  1218.         retour->statuscode=HTTP_OK;
  1219.         retour->keep_alive=0;
  1220.         strcpybuff(retour->msg, "Unknown, assuming junky server");
  1221.         strcpybuff(retour->contenttype,HTS_HYPERTEXT_DEFAULT_MIME);
  1222.       }
  1223.     }
  1224.   } else {  // vide!
  1225.     /*
  1226.     retour->statuscode=STATUSCODE_INVALID;
  1227.     strcpybuff(retour->msg,"Empty reponse or internal error");
  1228.     */
  1229.     /* This is dirty .. */
  1230.     retour->statuscode=HTTP_OK;
  1231.     strcpybuff(retour->msg, "Unknown, assuming junky server");
  1232.     strcpybuff(retour->contenttype,HTS_HYPERTEXT_DEFAULT_MIME);
  1233.   }
  1234. }
  1235.  
  1236. // traiter ligne par ligne l'en tΩte
  1237. // gestion des cookies
  1238. void treathead(t_cookie* cookie,char* adr,char* fil,htsblk* retour,char* rcvd) {
  1239.   int p;
  1240.   if ((p=strfield(rcvd,"Content-length:"))!=0) {
  1241. #if HDEBUG
  1242.     printf("ok, Content-length: dΘtectΘ\n");
  1243. #endif
  1244.     sscanf(rcvd+p,LLintP,&(retour->totalsize));
  1245.     if (retour->totalsize == 0) {
  1246.       retour->empty = 1;
  1247.     }
  1248.   }
  1249.   else if ((p=strfield(rcvd,"Content-Disposition:"))!=0) {
  1250.     while(is_realspace(*(rcvd+p))) p++;    // sauter espaces
  1251.     if ((int) strlen(rcvd+p)<250) { // pas trop long?
  1252.       char tmp[256];
  1253.       char *a=NULL,*b=NULL;
  1254.       strcpybuff(tmp,rcvd+p);
  1255.       a=strstr(tmp,"filename=");
  1256.       if (a) {
  1257.         a+=strlen("filename=");
  1258.         while(is_space(*a)) a++;
  1259.         //a=strchr(a,'"');
  1260.         if (a) {
  1261.           char *c=NULL;
  1262.           //a++;      /* jump " */
  1263.           while((c=strchr(a,'/')))    /* skip all / (see RFC2616) */
  1264.             a=c+1;
  1265.           //b=strchr(a+1,'"');
  1266.           b=a+strlen(a)-1;
  1267.           while(is_space(*b)) b--;
  1268.           b++;
  1269.           if (b) {
  1270.             *b='\0';
  1271.             if ((int) strlen(a) < 200) { // pas trop long?
  1272.               strcpybuff(retour->cdispo,a);
  1273.             }
  1274.           }
  1275.         }
  1276.       } 
  1277.     }
  1278.   }
  1279.   else if ((p=strfield(rcvd,"Last-Modified:"))!=0) {
  1280.     while(is_realspace(*(rcvd+p))) p++;    // sauter espaces
  1281.     if ((int) strlen(rcvd+p)<64) { // pas trop long?
  1282.       //struct tm* tm_time=convert_time_rfc822(rcvd+p);
  1283.       strcpybuff(retour->lastmodified,rcvd+p);
  1284.     }
  1285.   }
  1286.   else if ((p=strfield(rcvd,"Date:"))!=0) {
  1287.     if (strnotempty(retour->lastmodified)==0) {          /* pas encore de last-modified */
  1288.       while(is_realspace(*(rcvd+p))) p++;    // sauter espaces
  1289.       if ((int) strlen(rcvd+p)<64) { // pas trop long?
  1290.         //struct tm* tm_time=convert_time_rfc822(rcvd+p);
  1291.         strcpybuff(retour->lastmodified,rcvd+p);
  1292.       }
  1293.     }
  1294.   }
  1295.   else if ((p=strfield(rcvd,"Etag:"))!=0) {   /* Etag */
  1296.     if (retour) {
  1297.       while(is_realspace(*(rcvd+p))) p++;    // sauter espaces
  1298.       if ((int) strlen(rcvd+p)<64)  // pas trop long?
  1299.         strcpybuff(retour->etag,rcvd+p);
  1300.       else    // erreur.. ignorer
  1301.         retour->etag[0]='\0';
  1302.     }
  1303.   }
  1304.   // else if ((p=strfield(rcvd,"Transfer-Encoding: chunked"))!=0) {  // chunk!
  1305.   else if ((p=strfield(rcvd,"Transfer-Encoding:"))!=0) {  // chunk!
  1306.     while(is_realspace(*(rcvd+p))) p++;    // sauter espaces
  1307.     if (strfield(rcvd+p,"chunked")) {
  1308.       retour->is_chunk=1;     // chunked
  1309.       //retour->http11=2;     // chunked
  1310. #if HDEBUG
  1311.       printf("ok, Transfer-Encoding: dΘtectΘ\n");
  1312. #endif
  1313.     }
  1314.   }
  1315.   else if ((p=strfield(rcvd,"Content-type:"))!=0) {
  1316.     if (retour) {
  1317.       char tempo[1100];
  1318.       // Θviter les text/html; charset=foo
  1319.       {
  1320.         char* a=strchr(rcvd+p,';');
  1321.         if (a) {   // extended information
  1322.           *a='\0';
  1323.           a++;
  1324.               while(is_space(*a)) a++;
  1325.           if (strfield(a, "charset")) {
  1326.             a += 7;
  1327.                 while(is_space(*a)) a++;
  1328.             if (*a == '=') {
  1329.               a++;
  1330.                   while(is_space(*a)) a++;
  1331.               if (*a == '\"') a++;
  1332.                   while(is_space(*a)) a++;
  1333.               if (*a) {
  1334.                 char* chs = a;
  1335.                 while(*a && !is_space(*a) && *a != '\"' && *a != ';') a++;
  1336.                 *a = '\0';
  1337.                 if (*chs) {
  1338.                   if (strlen(chs) < sizeof(retour->charset) - 2) {
  1339.                     strcpybuff(retour->charset, chs);
  1340.                   }
  1341.                 }
  1342.               }
  1343.             }
  1344.           }
  1345.         }
  1346.       }
  1347.       sscanf(rcvd+p,"%s",tempo);
  1348.       if (strlen(tempo) < sizeof(retour->contenttype) - 2)    // pas trop long!!
  1349.         strcpybuff(retour->contenttype,tempo);
  1350.       else
  1351.         strcpybuff(retour->contenttype,"application/octet-stream-unknown");    // erreur
  1352.     }
  1353.   }
  1354.   else if ((p=strfield(rcvd,"Content-Range:"))!=0) {
  1355.     char* a=strstr(rcvd+p,"*/");
  1356.     if (a) {
  1357.       if (sscanf(a+2,LLintP,&retour->crange) != 1) {
  1358.         retour->crange=0;
  1359.       }
  1360.     }
  1361.   }
  1362.   else if ((p=strfield(rcvd,"Connection:"))!=0) {
  1363.         char* a = rcvd + p;
  1364.         while(is_space(*a)) a++;
  1365.         if (*a) {
  1366.             if (strfield(a, "Keep-Alive")) {
  1367.         if (!retour->keep_alive) {
  1368.           retour->keep_alive_max = 10;
  1369.           retour->keep_alive_t = 15;
  1370.         }
  1371.         retour->keep_alive = 1;
  1372.       } else {
  1373.                 retour->keep_alive = 0;
  1374.       }
  1375.         }
  1376.     }
  1377.   else if ((p=strfield(rcvd,"Keep-Alive:"))!=0) {
  1378.         char* a = rcvd + p;
  1379.         while(is_space(*a)) a++;
  1380.         if (*a) {
  1381.       char* p;
  1382.       retour->keep_alive = 1;
  1383.       retour->keep_alive_max = 10;
  1384.       retour->keep_alive_t = 15;
  1385.       if ((p=strstr(a, "timeout="))) {
  1386.         p+=strlen("timeout=");
  1387.         sscanf(p, "%d", &retour->keep_alive_t);
  1388.       }
  1389.       if ((p=strstr(a, "max="))) {
  1390.         p+=strlen("max=");
  1391.         sscanf(p, "%d", &retour->keep_alive_max);
  1392.       }
  1393.       if (retour->keep_alive_max <= 1 || retour->keep_alive_t < 3) {
  1394.         retour->keep_alive = 0;
  1395.       }
  1396.     }
  1397.   }
  1398.   else if ((p=strfield(rcvd,"TE:"))!=0) {
  1399.         char* a = rcvd + p;
  1400.         while(is_space(*a)) a++;
  1401.         if (*a) {
  1402.       if (strfield(a, "trailers")) {
  1403.         retour->keep_alive_trailers=1;
  1404.       }
  1405.     }
  1406.   }
  1407.     else if ((p=strfield(rcvd,"Content-Encoding:"))!=0) {
  1408.         if (retour) {
  1409.             char tempo[1100];
  1410.       char* a = rcvd + p;
  1411.       while(is_space(*a)) a++;
  1412.             {
  1413.                 char* a=strchr(rcvd+p,';');
  1414.                 if (a) *a='\0';
  1415.             }
  1416.             sscanf(a,"%s",tempo);
  1417.       if (strlen(tempo)<64)    // pas trop long!!
  1418.         strcpybuff(retour->contentencoding,tempo);
  1419.       else
  1420.         retour->contentencoding[0]='\0';    // erreur
  1421. #if HTS_USEZLIB
  1422.       /* Check known encodings */
  1423.       if (retour->contentencoding[0]) {
  1424.         if (
  1425.           (strfield2(retour->contentencoding, "gzip"))
  1426.           || (strfield2(retour->contentencoding, "x-gzip"))
  1427.           /*
  1428.           || (strfield2(retour->contentencoding, "compress"))
  1429.           || (strfield2(retour->contentencoding, "x-compress"))
  1430.           */
  1431.           || (strfield2(retour->contentencoding, "deflate"))
  1432.           || (strfield2(retour->contentencoding, "x-deflate"))
  1433.           ) {
  1434.         retour->compressed=1;
  1435.         }
  1436.       }
  1437. #endif
  1438.     }
  1439.   }
  1440.   else if ((p=strfield(rcvd,"Location:"))!=0) {
  1441.     if (retour) {
  1442.       if (retour->location) {
  1443.         while(is_realspace(*(rcvd+p))) p++;    // sauter espaces
  1444.         if ((int) strlen(rcvd+p)<HTS_URLMAXSIZE)  // pas trop long?
  1445.           strcpybuff(retour->location,rcvd+p);
  1446.         else    // erreur.. ignorer
  1447.           retour->location[0]='\0';
  1448.       }
  1449.     }
  1450.   }
  1451.   else if ( ((p=strfield(rcvd,"Set-Cookie:"))!=0) && (cookie) ) {    // ohh un cookie
  1452.     char* a = rcvd+p;           // pointeur
  1453.     char domain[256];           // domaine cookie (.netscape.com)
  1454.     char path[256];             // chemin (/)
  1455.     char cook_name[256];        // nom cookie (MYCOOK)
  1456.     char BIGSTK cook_value[8192];      // valeur (ID=toto,S=1234)
  1457. #if DEBUG_COOK
  1458.     printf("set-cookie detected\n");
  1459. #endif
  1460.     while(*a) {
  1461.       char *token_st,*token_end;
  1462.       char *value_st,*value_end;
  1463.       char name[256];
  1464.       char BIGSTK value[8192];
  1465.       int next=0;
  1466.       name[0]=value[0]='\0';
  1467.       //
  1468.  
  1469.       // initialiser cookie lu actuellement
  1470.       if (adr)
  1471.         strcpybuff(domain,jump_identification(adr));     // domaine
  1472.       strcpybuff(path,"/");         // chemin (/)
  1473.       strcpybuff(cook_name,"");     // nom cookie (MYCOOK)
  1474.       strcpybuff(cook_value,"");    // valeur (ID=toto,S=1234)
  1475.       // boucler jusqu'au prochain cookie ou la fin
  1476.       do {
  1477.         char* start_loop=a;
  1478.         while(is_space(*a)) a++;    // sauter espaces
  1479.         token_st=a;                 // dΘpart token
  1480.         while((!is_space(*a)) && (*a) && (*a!=';') && (*a!='=')) a++;    // arrΩter si espace, point virgule
  1481.         token_end=a;
  1482.         while(is_space(*a)) a++;    // sauter espaces
  1483.         if (*a=='=') {    // name=value
  1484.           a++;
  1485.           while(is_space(*a)) a++;    // sauter espaces
  1486.           value_st=a;
  1487.           while( (*a!=';') && (*a)) a++;    // prochain ;
  1488.           //while( ((*a!='"') || (*(a-1)=='\\')) && (*a)) a++;    // prochain " (et pas \")
  1489.           value_end=a;
  1490.           //if (*a==';') {  // finit par un ;
  1491.           // vΘrifier dΘbordements
  1492.           if ( (((int) (token_end - token_st))<200) && (((int) (value_end - value_st))<8000)
  1493.             && (((int) (token_end - token_st))>0)   && (((int) (value_end - value_st))>0) ) 
  1494.           {
  1495.             int name_len = (int) (token_end - token_st);
  1496.             int value_len = (int) (value_end - value_st);
  1497.             name[0]='\0';
  1498.             value[0]='\0';
  1499.             strncatbuff(name,token_st,name_len);
  1500.             strncatbuff(value,value_st,value_len);
  1501. #if DEBUG_COOK
  1502.             printf("detected cookie-av: name=\"%s\" value=\"%s\"\n",name,value);
  1503. #endif
  1504.             if (strfield2(name,"domain")) {
  1505.               if (value_len < sizeof(domain) - 1) {
  1506.                 strcpybuff(domain,value);
  1507.               } else {
  1508.                 cook_name[0] = 0;
  1509.                 break;
  1510.               }
  1511.             }
  1512.             else if (strfield2(name,"path")) {
  1513.               if (value_len < sizeof(path) - 1) {
  1514.                 strcpybuff(path,value);
  1515.               } else {
  1516.                 cook_name[0] = 0;
  1517.                 break;
  1518.               }
  1519.             }
  1520.             else if (strfield2(name,"max-age")) {
  1521.               // ignorΘ..
  1522.             }
  1523.             else if (strfield2(name,"expires")) {
  1524.               // ignorΘ..
  1525.             }
  1526.             else if (strfield2(name,"version")) {
  1527.               // ignorΘ..
  1528.             }
  1529.             else if (strfield2(name,"comment")) {
  1530.               // ignorΘ
  1531.             }
  1532.             else if (strfield2(name,"secure")) {    // ne devrait pas arriver ici
  1533.               // ignorΘ
  1534.             }
  1535.             else {
  1536.               if (value_len < sizeof(cook_value) - 1 && name_len < sizeof(cook_name) - 1) {
  1537.                 if (strnotempty(cook_name)==0) {          // noter premier: nom et valeur cookie
  1538.                   strcpybuff(cook_name,name);
  1539.                   strcpybuff(cook_value,value);
  1540.                 } else {                             // prochain cookie
  1541.                   a=start_loop;      // on devra recommencer α cette position
  1542.                   next=1;            // enregistrer
  1543.                 }
  1544.               } else {
  1545.                 cook_name[0] = 0;
  1546.                 break;
  1547.               }
  1548.             }
  1549.           }
  1550.         }
  1551.         if (!next) {
  1552.           while((*a!=';') && (*a)) a++;    // prochain
  1553.           while(*a==';') a++;             // sauter ;
  1554.         }
  1555.       } while((*a) && (!next));
  1556.       if (strnotempty(cook_name)) {          // cookie?
  1557. #if DEBUG_COOK
  1558.         printf("new cookie: name=\"%s\" value=\"%s\" domain=\"%s\" path=\"%s\"\n",cook_name,cook_value,domain,path);
  1559. #endif
  1560.         cookie_add(cookie,cook_name,cook_value,domain,path);
  1561.       }
  1562.     }
  1563.   }
  1564. }
  1565.  
  1566.  
  1567. // transforme le message statuscode en chaεne
  1568. HTSEXT_API void infostatuscode(char* msg,int statuscode) {
  1569.   switch( statuscode) {    
  1570.     // Erreurs HTTP, selon RFC
  1571.   case 100: strcpybuff( msg,"Continue"); break; 
  1572.   case 101: strcpybuff( msg,"Switching Protocols"); break; 
  1573.   case 200: strcpybuff( msg,"OK"); break; 
  1574.   case 201: strcpybuff( msg,"Created"); break; 
  1575.   case 202: strcpybuff( msg,"Accepted"); break; 
  1576.   case 203: strcpybuff( msg,"Non-Authoritative Information"); break; 
  1577.   case 204: strcpybuff( msg,"No Content"); break; 
  1578.   case 205: strcpybuff( msg,"Reset Content"); break; 
  1579.   case 206: strcpybuff( msg,"Partial Content"); break; 
  1580.   case 300: strcpybuff( msg,"Multiple Choices"); break; 
  1581.   case 301: strcpybuff( msg,"Moved Permanently"); break; 
  1582.   case 302: strcpybuff( msg,"Moved Temporarily"); break; 
  1583.   case 303: strcpybuff( msg,"See Other"); break; 
  1584.   case 304: strcpybuff( msg,"Not Modified"); break; 
  1585.   case 305: strcpybuff( msg,"Use Proxy"); break; 
  1586.   case 306: strcpybuff( msg,"Undefined 306 error"); break; 
  1587.   case 307: strcpybuff( msg,"Temporary Redirect"); break; 
  1588.   case 400: strcpybuff( msg,"Bad Request"); break; 
  1589.   case 401: strcpybuff( msg,"Unauthorized"); break; 
  1590.   case 402: strcpybuff( msg,"Payment Required"); break; 
  1591.   case 403: strcpybuff( msg,"Forbidden"); break; 
  1592.   case 404: strcpybuff( msg,"Not Found"); break; 
  1593.   case 405: strcpybuff( msg,"Method Not Allowed"); break; 
  1594.   case 406: strcpybuff( msg,"Not Acceptable"); break; 
  1595.   case 407: strcpybuff( msg,"Proxy Authentication Required"); break; 
  1596.   case 408: strcpybuff( msg,"Request Time-out"); break; 
  1597.   case 409: strcpybuff( msg,"Conflict"); break; 
  1598.   case 410: strcpybuff( msg,"Gone"); break; 
  1599.   case 411: strcpybuff( msg,"Length Required"); break; 
  1600.   case 412: strcpybuff( msg,"Precondition Failed"); break; 
  1601.   case 413: strcpybuff( msg,"Request Entity Too Large"); break; 
  1602.   case 414: strcpybuff( msg,"Request-URI Too Large"); break; 
  1603.   case 415: strcpybuff( msg,"Unsupported Media Type"); break; 
  1604.   case 416: strcpybuff( msg,"Requested Range Not Satisfiable"); break; 
  1605.   case 417: strcpybuff( msg,"Expectation Failed"); break; 
  1606.   case 500: strcpybuff( msg,"Internal Server Error"); break; 
  1607.   case 501: strcpybuff( msg,"Not Implemented"); break; 
  1608.   case 502: strcpybuff( msg,"Bad Gateway"); break; 
  1609.   case 503: strcpybuff( msg,"Service Unavailable"); break; 
  1610.   case 504: strcpybuff( msg,"Gateway Time-out"); break; 
  1611.   case 505: strcpybuff( msg,"HTTP Version Not Supported"); break; 
  1612.     //
  1613.   default: if (strnotempty(msg)==0) strcpybuff( msg,"Unknown error"); break;
  1614.   }
  1615. }
  1616.  
  1617.  
  1618. // identique au prΘcΘdent, sauf que l'on donne adr+fil et non url complΦte
  1619. htsblk xhttpget(httrackp *opt,char* adr,char* fil) {
  1620.   T_SOC soc;
  1621.   htsblk retour;
  1622.   
  1623.   memset(&retour, 0, sizeof(htsblk));
  1624.   soc=http_fopen(opt,adr,fil,&retour);
  1625.  
  1626.   if (soc!=INVALID_SOCKET) {
  1627.     http_fread(soc,&retour);
  1628. #if HTS_DEBUG_CLOSESOCK
  1629.     DEBUG_W("xhttpget: deletehttp\n");
  1630. #endif
  1631.     if (retour.soc!=INVALID_SOCKET) deletehttp(&retour);  // fermer
  1632.     retour.soc=INVALID_SOCKET;
  1633.   }
  1634.   return retour;
  1635. }
  1636.  
  1637. // variation sur un thΦme...
  1638. // rΘceptionne uniquement un en-tΩte (HEAD)
  1639. // retourne dans xx.adr l'adresse pointant sur le bloc de mΘmoire de l'en tΩte
  1640. htsblk http_gethead(httrackp *opt,char* adr,char* fil) {
  1641.   T_SOC soc;
  1642.   htsblk retour;
  1643.  
  1644.   memset(&retour, 0, sizeof(htsblk));
  1645.   soc=http_xfopen(opt,1,0,1,NULL,adr,fil,&retour);  // HEAD, pas de traitement en-tΩte
  1646.  
  1647.   if (soc!=INVALID_SOCKET) {
  1648.     http_fread(soc,&retour);    // rΘception en-tΩte
  1649. #if HTS_DEBUG_CLOSESOCK
  1650.     DEBUG_W("http_gethead: deletehttp\n");
  1651. #endif
  1652.     if (retour.soc!=INVALID_SOCKET) deletehttp(&retour);  // fermer
  1653.     retour.soc=INVALID_SOCKET;
  1654.   }
  1655.   return retour;
  1656. }
  1657. // oui ca ressemble vachement α xhttpget - en Θtant sobre on peut voir LA diffΘrence..
  1658.  
  1659.  
  1660. // lecture sur une socket ouverte, le header a dΘja ΘtΘ envoyΘ dans le cas de GET
  1661. // il ne reste plus qu'α lire les donnΘes
  1662. // (pour HEAD le header est lu ici!)
  1663. void http_fread(T_SOC soc,htsblk* retour) {  
  1664.   //int bufl=TAILLE_BUFFER;    // 8Ko de buffer
  1665.   
  1666.   if (retour) retour->soc=soc;
  1667.   if (soc!=INVALID_SOCKET) {    
  1668.     // fonction de lecture d'une socket (plus propre)
  1669.     while(http_fread1(retour)!=-1);
  1670.     soc=retour->soc;
  1671.     if (retour->adr==NULL) {
  1672.       if (strnotempty(retour->msg)==0)
  1673.         sprintf(retour->msg,"Unable to read");
  1674.       return ;    // erreur
  1675.     } 
  1676.     
  1677. #if HDEBUG
  1678.     printf("Ok, donnΘes reτues\n");
  1679. #endif   
  1680.  
  1681.     return ;
  1682.     
  1683.   } 
  1684.   
  1685.   return ;
  1686. }
  1687.  
  1688. // check if data is available
  1689. int check_readinput(htsblk* r) {
  1690.   if (r->soc != INVALID_SOCKET) {
  1691.     fd_set fds;           // poll structures
  1692.     struct timeval tv;          // structure for select
  1693.     FD_ZERO(&fds);
  1694.     FD_SET(r->soc,&fds);           
  1695.     tv.tv_sec=0;
  1696.     tv.tv_usec=0;
  1697.     select(r->soc + 1,&fds,NULL,NULL,&tv);
  1698.     if (FD_ISSET(r->soc,&fds))
  1699.       return 1;
  1700.     else
  1701.       return 0;
  1702.   } else
  1703.     return 0;
  1704. }
  1705.  
  1706. // check if data is available
  1707. int check_readinput_t(T_SOC soc, int timeout) {
  1708.   if (soc != INVALID_SOCKET) {
  1709.     fd_set fds;           // poll structures
  1710.     struct timeval tv;          // structure for select
  1711.     FD_ZERO(&fds);
  1712.     FD_SET(soc,&fds);           
  1713.     tv.tv_sec=timeout;
  1714.     tv.tv_usec=0;
  1715.     select(soc + 1,&fds,NULL,NULL,&tv);
  1716.     if (FD_ISSET(soc,&fds))
  1717.       return 1;
  1718.     else
  1719.       return 0;
  1720.   } else
  1721.     return 0;
  1722. }
  1723.  
  1724.  
  1725. // lecture d'un bloc sur une socket (ou un fichier!)
  1726. // >=0 : nombre d'octets lus
  1727. // <0 : fin ou erreur
  1728. HTS_INLINE LLint http_fread1(htsblk* r) {
  1729.   //int bufl=TAILLE_BUFFER;  // taille d'un buffer max.
  1730.   return http_xfread1(r,TAILLE_BUFFER);
  1731. }
  1732.  
  1733. // idem, sauf qu'ici on peut choisir la taille max de donnΘes α recevoir
  1734. // SI bufl==0 alors le buffer est censΘ Ωtre de 8kos, et on recoit par bloc de lignes
  1735. // en Θliminant les cr (ex: header), arrΩt si double-lf
  1736. // SI bufl==-1 alors le buffer est censΘ Ωtre de 8kos, et on recoit ligne par ligne
  1737. // en Θliminant les cr (ex: header), arrΩt si double-lf
  1738. // Note: les +1 dans les malloc sont d√s α l'octet nul rajoutΘ en fin de fichier
  1739. LLint http_xfread1(htsblk* r,int bufl) {
  1740.   int nl=-1;
  1741.  
  1742.   // EOF
  1743.   if (r->totalsize > 0 && r->size == r->totalsize) {
  1744.     return READ_EOF;
  1745.   }
  1746.  
  1747.   if (bufl>0) {
  1748.     if (!r->is_write) {     // stocker en mΘmoire
  1749.       if (r->totalsize>0) {    // totalsize dΘterminΘ ET ALLOUE
  1750.         if (r->adr==NULL) {
  1751.           r->adr = (char*) malloct((size_t) r->totalsize + 1);
  1752.           r->size = 0;
  1753.         }
  1754.         if (r->adr != NULL) {
  1755.           // lecture
  1756.           nl = hts_read(r,r->adr + ((int) r->size),(int) (r->totalsize-r->size) );     /* NO 32 bit overlow possible here (no 4GB html!) */
  1757.           // nouvelle taille
  1758.           if (nl >= 0) r->size+=nl;
  1759.  
  1760.           /*
  1761.           if (r->size >= r->totalsize)
  1762.             nl = -1;  // break
  1763.           */
  1764.           
  1765.           r->adr[r->size]='\0';    // caractΦre NULL en fin au cas o∙ l'on traite des HTML
  1766.         }
  1767.         
  1768.       } else {                 // inconnu..
  1769.         // rΘserver de la mΘmoire?
  1770.         if (r->adr==NULL) {
  1771. #if HDEBUG
  1772.           printf("..alloc xfread\n");
  1773. #endif
  1774.           r->adr=(char*) malloct(bufl + 1);
  1775.           r->size=0;
  1776.         }
  1777.         else {
  1778. #if HDEBUG
  1779.           printf("..realloc xfread1\n");
  1780. #endif
  1781.           r->adr=(char*) realloct(r->adr,(int)r->size+bufl + 1);
  1782.         }
  1783.         
  1784.         if (r->adr!=NULL) {
  1785.           // lecture
  1786.           nl = hts_read(r,r->adr+(int)r->size,bufl);
  1787.           if (nl > 0) {
  1788.             // resize
  1789.             r->adr=(char*) realloct(r->adr,(int)r->size+nl + 1);
  1790.             // nouvelle taille
  1791.             r->size+=nl;
  1792.             // octet nul
  1793.             if (r->adr) r->adr[r->size]='\0';
  1794.  
  1795.           } // sinon on a fini
  1796. #if HDEBUG
  1797.           else if (nl < 0)
  1798.             printf("..end read (%d)\n", nl);
  1799. #endif
  1800.         }
  1801. #if HDEBUG
  1802.         else printf("..-> error\n");
  1803. #endif
  1804.       }
  1805.  
  1806.       // pas de adr=erreur
  1807.       if (r->adr == NULL) nl = READ_ERROR;
  1808.  
  1809.     } else {    // stocker sur disque
  1810.       char* buff;
  1811.       buff=(char*) malloct(bufl);
  1812.       if (buff!=NULL) {
  1813.         // lecture
  1814.         nl = hts_read(r,buff,bufl);
  1815.         // nouvelle taille
  1816.         if (nl > 0) { 
  1817.           r->size+=nl;
  1818.           if (fwrite(buff,1,nl,r->out)!=nl) {
  1819.             r->statuscode=STATUSCODE_INVALID;
  1820.             strcpybuff(r->msg,"Write error on disk");
  1821.             nl=READ_ERROR;
  1822.           }
  1823.         }
  1824.  
  1825.         //if ((nl < 0) || ((r->totalsize>0) && (r->size >= r->totalsize)))
  1826.         //  nl=-1;  // break
  1827.  
  1828.         // libΘrer bloc tempo
  1829.         freet(buff);
  1830.       } else
  1831.         nl=READ_ERROR;
  1832.       
  1833.       if ((nl < 0) && (r->out!=NULL)) {
  1834.         fflush(r->out); 
  1835.       }
  1836.         
  1837.         
  1838.     } // stockage disque ou mΘmoire
  1839.  
  1840.   } else if (bufl == -2) {  // force reserve
  1841.     if (r->adr==NULL) {
  1842.       r->adr=(char*) malloct(8192);
  1843.       r->size=0;
  1844.       return 0;
  1845.     }
  1846.     return -1;
  1847.   } else {    // rΘception d'un en-tΩte octet par octet
  1848.     int count=256;
  1849.     int tot_nl=0;
  1850.     int lf_detected=0;
  1851.     int at_begining=1;
  1852.     do {
  1853.       nl = READ_INTERNAL_ERROR;
  1854.       count--;
  1855.       if (r->adr==NULL) {
  1856.         r->adr=(char*) malloct(8192);
  1857.         r->size=0;
  1858.       }
  1859.       if (r->adr!=NULL) {
  1860.         if (r->size < 8190) {
  1861.           // lecture
  1862.           nl = hts_read(r,r->adr+r->size,1);
  1863.           if (nl > 0) {
  1864.             // exit if:
  1865.             // lf detected AND already detected before
  1866.             // or
  1867.             // lf detected AND first character read
  1868.             if (*(r->adr+r->size) == 10) {
  1869.               if (lf_detected || (at_begining) || (bufl<0))
  1870.                 count=-1;
  1871.               lf_detected=1;
  1872.             }
  1873.             if (*(r->adr+r->size) != 13) {   // sauter caractΦres 13
  1874.               if (
  1875.                 (*(r->adr+r->size) != 10)
  1876.                 &&
  1877.                 (*(r->adr+r->size) != 13)
  1878.                 ) {
  1879.                 // restart for new line
  1880.                 lf_detected=0;
  1881.               }
  1882.               (r->size)++;
  1883.               at_begining=0;
  1884.             }
  1885.             *(r->adr+r->size)='\0';    // terminer par octet nul
  1886.           }
  1887.         }
  1888.       }
  1889.       if (nl >= 0) {
  1890.         tot_nl+=nl;
  1891.         if (!check_readinput(r))
  1892.           count=-1;
  1893.       }
  1894.     } while((nl >= 0) && (count>0));
  1895.     if (nl >= 0) {
  1896.       nl = tot_nl;
  1897.     }
  1898.   }
  1899.   // EOF
  1900.   if (r->totalsize > 0 && r->size == r->totalsize) {
  1901.     return READ_EOF;
  1902.   } else {
  1903.     return nl;
  1904.   }
  1905. }
  1906.  
  1907.  
  1908. // teste une adresse, et suit l'Θventuel chemin "moved"
  1909. // retourne 200 ou le code d'erreur (404=NOT FOUND, etc)
  1910. // copie dans loc la vΘritable adresse si celle-ci est diffΘrente
  1911. htsblk http_location(httrackp *opt,char* adr,char* fil,char* loc) {
  1912.   htsblk retour;
  1913.   int retry=0;
  1914.   int tryagain;
  1915.   // note: "RFC says"
  1916.   // 5 boucles au plus, on en teste au plus 8 ici
  1917.   // sinon abandon..
  1918.   do {
  1919.     tryagain=0;
  1920.     switch ((retour=http_test(opt,adr,fil,loc)).statuscode) {
  1921.     case HTTP_OK:
  1922.       break;   // ok!
  1923.     case HTTP_MOVED_PERMANENTLY:
  1924.     case HTTP_FOUND:
  1925.     case HTTP_SEE_OTHER:
  1926.     case HTTP_TEMPORARY_REDIRECT: // moved!
  1927.       // recalculer adr et fil!
  1928.       if (ident_url_absolute(loc,adr,fil)!=-1) {
  1929.         tryagain=1;  // retenter
  1930.         retry++;     // ..encore une fois
  1931.       }
  1932.     }
  1933.   } while((tryagain) && (retry<5+3));
  1934.   return retour;
  1935. }
  1936.  
  1937.  
  1938. // teste si une URL (validitΘ, header, taille)
  1939. // retourne 200 ou le code d'erreur (404=NOT FOUND, etc)
  1940. // en cas de moved xx, dans location
  1941. // abandonne dΘsormais au bout de 30 secondes (aurevoir les sites
  1942. // qui nous font poireauter 5 heures..) -> -2=timeout
  1943. htsblk http_test(httrackp *opt,char* adr,char* fil,char* loc) {
  1944.   T_SOC soc;
  1945.   htsblk retour;
  1946.   //int rcvsize=-1;
  1947.   //char* rcv=NULL;    // adresse de retour
  1948.   //int bufl=TAILLE_BUFFER;    // 8Ko de buffer
  1949.   TStamp tl;
  1950.   int timeout=30;  // timeout pour un check (arbitraire) // **
  1951.  
  1952.   // pour abandonner un site trop lent
  1953.   tl=time_local();
  1954.  
  1955.   loc[0]='\0';
  1956.   memset(&retour, 0, sizeof(htsblk));    // effacer
  1957.   retour.location=loc;    // si non nul, contiendra l'adresse vΘritable en cas de moved xx
  1958.  
  1959.   //soc=http_fopen(adr,fil,&retour,NULL);  // ouvrir, + header
  1960.  
  1961.   // on ouvre en head, et on traite l'en tΩte
  1962.   soc=http_xfopen(opt,1,0,1,NULL,adr,fil,&retour);  // ouvrir HEAD, + envoi header
  1963.   
  1964.   if (soc!=INVALID_SOCKET) {
  1965.     int e=0;
  1966.     // tant qu'on a des donnΘes, et qu'on ne recoit pas deux LF, et que le timeout n'arrie pas
  1967.     do {
  1968.       if (http_xfread1(&retour,0) < 0)
  1969.         e=1;
  1970.       else {
  1971.         if (retour.adr!=NULL) {
  1972.           if ((retour.adr[retour.size-1]!=10) || (retour.adr[retour.size-2]!=10))
  1973.             e=1;
  1974.         }
  1975.       }
  1976.             
  1977.       if (!e) {
  1978.         if ((time_local()-tl)>=timeout) {
  1979.           e=-1;
  1980.         }
  1981.       }
  1982.       
  1983.     } while (!e);
  1984.     
  1985.     if (e==1) {
  1986.       if (adr!=NULL) {
  1987.         int ptr=0;
  1988.         char rcvd[1100];
  1989.  
  1990.         // note: en gros recopie du traitement de back_wait()
  1991.         //
  1992.  
  1993.  
  1994.         // ----------------------------------------
  1995.         // traiter en-tΩte!
  1996.         // status-line α rΘcupΘrer
  1997.         ptr+=binput(retour.adr+ptr,rcvd,1024);
  1998.         if (strnotempty(rcvd)==0)
  1999.           ptr+=binput(retour.adr+ptr,rcvd,1024);    // "certains serveurs buggΘs envoient un \n au dΘbut" (RFC)
  2000.         
  2001.         // traiter status-line
  2002.         treatfirstline(&retour,rcvd);
  2003.         
  2004. #if HDEBUG
  2005.         printf("(Buffer) Status-Code=%d\n",retour.statuscode);
  2006. #endif
  2007.         
  2008.         // en-tΩte
  2009.         
  2010.         // header // ** !attention! HTTP/0.9 non supportΘ
  2011.         do {
  2012.           ptr+=binput(retour.adr+ptr,rcvd,1024);          
  2013. #if HDEBUG
  2014.           printf("(buffer)>%s\n",rcvd);      
  2015. #endif
  2016.           if (strnotempty(rcvd))
  2017.             treathead(NULL,NULL,NULL,&retour,rcvd);  // traiter
  2018.           
  2019.         } while(strnotempty(rcvd));
  2020.         // ----------------------------------------                    
  2021.         
  2022.         // libΘrer mΘmoire
  2023.         if (retour.adr!=NULL) { freet(retour.adr); retour.adr=NULL; }
  2024.       }
  2025.     } else {
  2026.       retour.statuscode=STATUSCODE_TIMEOUT;
  2027.       strcpybuff(retour.msg,"Timeout While Testing");
  2028.     }
  2029.     
  2030.     
  2031. #if HTS_DEBUG_CLOSESOCK
  2032.     DEBUG_W("http_test: deletehttp\n");
  2033. #endif
  2034.     deletehttp(&retour);
  2035.     retour.soc=INVALID_SOCKET;
  2036.   }
  2037.   return retour;    
  2038. }
  2039.  
  2040. // CrΘe un lien (http) vers une adresse internet iadr
  2041. // retour: structure (adresse, taille, message si erreur (si !adr))
  2042. // peut ouvrir avec des connect() non bloquants: waitconnect=0/1
  2043. int newhttp(httrackp *opt,const char* _iadr,htsblk* retour,int port,int waitconnect) {  
  2044.   t_fullhostent fullhostent_buffer;    // buffer pour resolver
  2045.   T_SOC soc;                           // descipteur de la socket
  2046.   char* iadr;
  2047.   // unsigned short int port;
  2048.   
  2049.   // si iadr="#" alors c'est une fausse URL, mais un vrai fichier
  2050.   // local.
  2051.   // utile pour les tests!
  2052.   //## if (iadr[0]!=lOCAL_CHAR) {
  2053.   if (strcmp(_iadr,"file://") != 0) {           /* non fichier */
  2054.     SOCaddr server;
  2055.     int server_size=sizeof(server);
  2056.     t_hostent* hp;    
  2057.     // effacer structure
  2058.     memset(&server, 0, sizeof(server));
  2059.  
  2060.     // tester un Θventuel id:pass et virer id:pass@ si dΘtectΘ
  2061.     iadr = jump_identification(_iadr);
  2062.   
  2063. #if HDEBUG
  2064.     printf("gethostbyname\n");
  2065. #endif
  2066.     
  2067.     // tester un Θventuel port
  2068.     if (port==-1) {
  2069.       char *a=jump_toport(iadr);
  2070. #if HTS_USEOPENSSL
  2071.       if (retour->ssl)
  2072.         port=443;
  2073.       else
  2074.         port=80;    // port par dΘfaut
  2075. #else
  2076.       port=80;    // port par dΘfaut
  2077. #endif
  2078.       if (a) {
  2079.         char BIGSTK iadr2[HTS_URLMAXSIZE*2];
  2080.         int i=-1;
  2081.         iadr2[0]='\0';
  2082.         sscanf(a+1,"%d",&i);
  2083.         if (i!=-1) {
  2084.           port=(unsigned short int) i;
  2085.         }
  2086.         
  2087.         // adresse vΘritable (sans :xx)
  2088.         strncatbuff(iadr2,iadr,(int) (a - iadr));
  2089.  
  2090.         // adresse sans le :xx
  2091.         hp = hts_gethostbyname(opt,iadr2, &fullhostent_buffer);
  2092.         
  2093.       } else {
  2094.  
  2095.         // adresse normale (port par dΘfaut par la suite)
  2096.         hp = hts_gethostbyname(opt,iadr, &fullhostent_buffer);
  2097.         
  2098.       }
  2099.       
  2100.     } else    // port dΘfini
  2101.       hp = hts_gethostbyname(opt,iadr, &fullhostent_buffer);
  2102.  
  2103.     
  2104.     // Conversion iadr -> adresse
  2105.     // structure recevant le nom de l'h⌠te, etc
  2106.     //struct     hostent     *hp;
  2107.     if (hp == NULL) {
  2108. #if DEBUG
  2109.       printf("erreur gethostbyname\n");
  2110. #endif
  2111.       if (retour && retour->msg) {
  2112. #ifdef _WIN32
  2113.         int last_errno = WSAGetLastError();
  2114.         sprintf(retour->msg,"Unable to get server's address: %s", strerror(last_errno));
  2115. #else
  2116.         int last_errno = errno;
  2117.         sprintf(retour->msg,"Unable to get server's address: %s", strerror(last_errno));
  2118. #endif
  2119.       }
  2120.       return INVALID_SOCKET;
  2121.     }  
  2122.     // copie adresse
  2123.     SOCaddr_copyaddr(server, server_size, hp->h_addr_list[0], hp->h_length);
  2124.     // make a copy for external clients
  2125.     retour->address_size = sizeof(retour->address);
  2126.     SOCaddr_copyaddr(retour->address, retour->address_size, hp->h_addr_list[0], hp->h_length);
  2127.     // memcpy(&SOCaddr_sinaddr(server), hp->h_addr_list[0], hp->h_length);
  2128.      
  2129.     // crΘer ("attachement") une socket (point d'accΦs) internet,en flot
  2130. #if HDEBUG
  2131.     printf("socket\n");
  2132. #endif
  2133. #if HTS_WIDE_DEBUG    
  2134.     DEBUG_W("socket\n");
  2135. #endif
  2136.     soc = (T_SOC) socket(SOCaddr_sinfamily(server), SOCK_STREAM, 0);
  2137.     if (retour != NULL) {
  2138.       retour->debugid = HTS_STAT.stat_sockid++;
  2139.     }
  2140. #if HTS_WIDE_DEBUG    
  2141.     DEBUG_W("socket()=%d\n" _ (int) soc);
  2142. #endif
  2143.     if (soc==INVALID_SOCKET) {
  2144.       if (retour && retour->msg) {
  2145. #ifdef _WIN32
  2146.         int last_errno = WSAGetLastError();
  2147.         sprintf(retour->msg,"Unable to create a socket: %s", strerror(last_errno));
  2148. #else
  2149.         int last_errno = errno;
  2150.         sprintf(retour->msg,"Unable to create a socket: %s", strerror(last_errno));
  2151. #endif
  2152.       }
  2153.       return INVALID_SOCKET;                        // erreur crΘation socket impossible
  2154.     }
  2155.  
  2156.     // bind this address
  2157.     if (retour != NULL && retour->req.proxy.bindhost[0] != 0) {
  2158.       t_fullhostent bind_buffer;
  2159.       hp = hts_gethostbyname(opt, retour->req.proxy.bindhost, &bind_buffer);
  2160.       if (hp == NULL ||
  2161.         bind(soc, (struct sockaddr *)hp->h_addr_list[0], hp->h_length) != 0) {
  2162.           if (retour && retour->msg) {
  2163. #ifdef _WIN32
  2164.             int last_errno = WSAGetLastError();
  2165.             sprintf(retour->msg,"Unable to bind the specificied server address: %s", strerror(last_errno));
  2166. #else
  2167.             int last_errno = errno;
  2168.             sprintf(retour->msg,"Unable to bind the specificied server address: %s", strerror(last_errno));
  2169. #endif
  2170.           }
  2171.           deletesoc(soc);
  2172.           return INVALID_SOCKET;
  2173.       }
  2174.     }
  2175.     
  2176.     // structure: connexion au domaine internet, port 80 (ou autre)
  2177.     SOCaddr_initport(server, port);
  2178. #if HDEBUG
  2179.     printf("==%d\n",soc);
  2180. #endif
  2181.  
  2182.     // connexion non bloquante?
  2183.     if (!waitconnect ) {
  2184.       unsigned long p=1;  // non bloquant
  2185. #ifdef _WIN32
  2186.       ioctlsocket(soc,FIONBIO,&p);
  2187. #else
  2188.       ioctl(soc,FIONBIO,&p);
  2189. #endif
  2190.     }
  2191.     
  2192.     // Connexion au serveur lui mΩme
  2193. #if HDEBUG
  2194.     printf("connect\n");
  2195. #endif
  2196.     HTS_STAT.last_connect = mtime_local();
  2197.     
  2198. #if HTS_WIDE_DEBUG
  2199.     DEBUG_W("connect\n");
  2200. #endif
  2201. #ifdef _WIN32
  2202.     if (connect(soc, (const struct sockaddr FAR *)&server, server_size) != 0) {
  2203. #else
  2204.       if (connect(soc, (struct sockaddr *)&server, server_size) == -1) {
  2205. #endif
  2206.  
  2207.         // bloquant
  2208.         if (waitconnect) {
  2209. #if HDEBUG
  2210.           printf("unable to connect!\n");
  2211. #endif
  2212.           if (retour && retour->msg) {
  2213. #ifdef _WIN32
  2214.             int last_errno = WSAGetLastError();
  2215.             sprintf(retour->msg,"Unable to connect to the server: %s", strerror(last_errno));
  2216. #else
  2217.             int last_errno = errno;
  2218.             sprintf(retour->msg,"Unable to connect to the server: %s", strerror(last_errno));
  2219. #endif
  2220.           }
  2221.           /* Close the socket and notify the error!!! */
  2222.           deletesoc(soc);
  2223.           return INVALID_SOCKET;
  2224.         }
  2225.       }
  2226. #if HTS_WIDE_DEBUG    
  2227.       DEBUG_W("connect done\n");
  2228. #endif
  2229.       
  2230. #if HDEBUG
  2231.       printf("connexion Θtablie\n");
  2232. #endif
  2233.     
  2234.     // A partir de maintenant, on peut envoyer et recevoir des donnΘes
  2235.     // via le flot identifiΘ par soc (socket): write(soc,adr,taille) et 
  2236.     // read(soc,adr,taille)
  2237.  
  2238.   } else {    // on doit ouvrir un fichier local!
  2239.     // il sera gΘrΘ de la mΩme maniΦre qu'une socket (c'est idem!)
  2240.  
  2241.     soc=LOCAL_SOCKET_ID;    // pseudo-socket locale..
  2242.     // soc sera remplacΘ lors d'un http_fopen() par un handle vΘritable!
  2243.  
  2244.   }   // teste fichier local ou http
  2245.   
  2246.   return soc;
  2247. }
  2248.  
  2249.  
  2250.  
  2251. // couper http://www.truc.fr/pub/index.html -> www.truc.fr /pub/index.html
  2252. // retour=-1 si erreur.
  2253. // si file://... alors adresse=file:// (et coupe le ?query dans ce cas)
  2254. int ident_url_absolute(const char* url,char* adr,char* fil) {
  2255.   int pos=0;
  2256.   int scheme=0;
  2257.  
  2258.   // effacer adr et fil
  2259.   adr[0]=fil[0]='\0';
  2260.   
  2261. #if HDEBUG
  2262.   printf("protocol: %s\n",url);
  2263. #endif
  2264.  
  2265.   // Scheme?
  2266.   {
  2267.     const char* a=url;
  2268.     while (isalpha((unsigned char)*a))
  2269.       a++;
  2270.     if (*a == ':')
  2271.       scheme=1;
  2272.   }
  2273.  
  2274.   // 1. optional scheme ":"
  2275.   if ((pos=strfield(url,"file:"))) {    // fichier local!! (pour les tests)
  2276.     //!!p+=3;
  2277.     strcpybuff(adr,"file://");
  2278.   } else if ((pos=strfield(url,"http:"))) {    // HTTP
  2279.     //!!p+=3;
  2280.   } else if ((pos=strfield(url,"ftp:"))) {    // FTP
  2281.     strcpybuff(adr,"ftp://");    // FTP!!
  2282.     //!!p+=3;
  2283. #if HTS_USEOPENSSL
  2284.   } else if (SSL_is_available && (pos=strfield(url,"https:"))) {    // HTTPS
  2285.     strcpybuff(adr,"https://");
  2286. #endif
  2287. #if HTS_USEMMS
  2288.   } else if ((pos = strfield(url,"mms:"))) {    // mms
  2289.     strcpybuff(adr,"mms://");
  2290. #endif
  2291.   } else if (scheme) {
  2292.     return -1;    // erreur non reconnu
  2293.   } else
  2294.     pos=0;
  2295.  
  2296.   // 2. optional "//" authority
  2297.   if (strncmp(url+pos,"//",2)==0)
  2298.     pos+=2;
  2299.  
  2300.   // (url+pos) now points to the path (not net path)
  2301.  
  2302.   //## if (adr[0]!=lOCAL_CHAR) {    // adresse normale http
  2303.   if (!strfield(adr,"file:")) {      // PAS file://
  2304.     const char *p,*q;
  2305.     p=url+pos;
  2306.  
  2307.     // p pointe sur le dΘbut de l'adresse, ex: www.truc.fr/sommaire/index.html
  2308.     q=strchr(jump_identification(p),'/');
  2309.     if (q==0) q=strchr(jump_identification(p),'?');     // http://www.foo.com?bar=1
  2310.     if (q==0) q=p+strlen(p);  // pointe sur \0
  2311.     // q pointe sur le chemin, ex: index.html?query=recherche
  2312.     
  2313.     // chemin www... trop long!!
  2314.     if ( ( ((int) (q - p)) )  > HTS_URLMAXSIZE) {
  2315.       //strcpybuff(retour.msg,"Path too long");
  2316.       return -1;    // erreur
  2317.     }
  2318.     
  2319.     // recopier adresse www..
  2320.     strncatbuff(adr,p, ((int) (q - p)) );
  2321.     // *( adr+( ((int) q) - ((int) p) ) )=0;  // faut arrΩter la fumette!
  2322.     // recopier chemin /pub/..
  2323.     if (q[0] != '/')    // page par dΘfaut (/)
  2324.       strcatbuff(fil,"/");
  2325.     strcatbuff(fil,q);
  2326.     // SECURITE:
  2327.     // simplifier url pour les ../
  2328.     fil_simplifie(fil);
  2329.   } else {    // localhost file://
  2330.     const char *p;
  2331.     int i;
  2332.     char* a;
  2333.     
  2334.     p=url+pos;
  2335.     if (*p == '/' || *p == '\\') {  /* file:///.. */
  2336.       strcatbuff(fil,p);    // fichier local ; adr="#"
  2337.     } else {
  2338.       if (p[1] != ':') {
  2339.         strcatbuff(fil,"//");   /* file://server/foo */
  2340.         strcatbuff(fil,p);
  2341.       } else {
  2342.         strcatbuff(fil,p);    // file://C:\..
  2343.       }
  2344.     }
  2345.     
  2346.     a=strchr(fil,'?');
  2347.     if (a) 
  2348.       *a='\0';      /* couper query (inutile pour file:// lors de la requΩte) */
  2349.     // filtrer les \\ -> / pour les fichiers DOS
  2350.     for(i=0;i<(int) strlen(fil);i++)
  2351.       if (fil[i]=='\\')
  2352.         fil[i]='/';
  2353.   }
  2354.  
  2355.   // no hostname
  2356.   if (!strnotempty(adr))
  2357.     return -1;    // erreur non reconnu
  2358.  
  2359.   // nommer au besoin.. (non utilisΘ normalement)
  2360.   if (!strnotempty(fil))
  2361.     strcpybuff(fil,"default-index.html");
  2362.  
  2363.   // case insensitive pour adresse
  2364.   {
  2365.     char *a=jump_identification(adr);
  2366.     while(*a) {
  2367.       if ((*a>='A') && (*a<='Z'))
  2368.         *a+='a'-'A';       
  2369.       a++;
  2370.     }
  2371.   }
  2372.   
  2373.   return 0;
  2374. }
  2375.  
  2376. /* simplify ../ and ./ */
  2377. void fil_simplifie(char* f) {
  2378.   char *a, *b;
  2379.   char *rollback[128];
  2380.   int rollid = 0;
  2381.   char lc = '/';
  2382.   int query = 0;
  2383.   int wasAbsolute = (*f == '/');
  2384.   for(a = b = f ; *a != '\0' ; ) {
  2385.     if (*a == '?')
  2386.       query = 1;
  2387.     if (query == 0 && lc == '/' && a[0] == '.' && a[1] == '/') {    /* foo/./bar or ./foo  */
  2388.       a += 2;
  2389.     }
  2390.     else if (query == 0 && lc == '/' && a[0] == '.' && a[1] == '.' && ( a[2] == '/' || a[2] == '\0' ) ) {    /* foo/../bar or ../foo or .. */
  2391.       if (a[2] == '\0')
  2392.         a += 2;
  2393.       else
  2394.         a += 3;
  2395.       if (rollid > 1) {
  2396.         rollid--;
  2397.         b = rollback[rollid - 1];
  2398.       } else {   /* too many ../ */
  2399.         rollid = 0;
  2400.         b = f;
  2401.         if (wasAbsolute)
  2402.           b++;   /* after the / */
  2403.       }
  2404.     }
  2405.     else {
  2406.       *b++ = lc = *a;
  2407.       if (*a == '/') {
  2408.         rollback[rollid++] = b;
  2409.         if (rollid >= 127) {
  2410.           *f = '\0';      /* ERROR */
  2411.           break;
  2412.         }
  2413.       }
  2414.       a++;
  2415.     }
  2416.   }
  2417.   *b = '\0';
  2418.   if (*f == '\0') {
  2419.     if (wasAbsolute) {
  2420.       f[0] = '/';
  2421.       f[1] = '\0';
  2422.     } else {
  2423.       f[0] = '.';
  2424.       f[1] = '/';
  2425.       f[2] = '\0';
  2426.     }
  2427.   }
  2428. }
  2429.  
  2430. // fermer liaison fichier ou socket
  2431. HTS_INLINE void deletehttp(htsblk* r) {
  2432. #if HTS_DEBUG_CLOSESOCK
  2433.     DEBUG_W("deletehttp: (htsblk*) 0x%p\n" _ (void*) r);
  2434. #endif
  2435. #if HTS_USEOPENSSL
  2436.     /* Free OpenSSL structures */
  2437.     if (SSL_is_available && r->ssl_con) {
  2438.       SSL_shutdown(r->ssl_con);
  2439.       SSL_free(r->ssl_con);
  2440.       r->ssl_con=NULL;
  2441.     }
  2442. #endif  
  2443.   if (r->soc!=INVALID_SOCKET) {
  2444.     if (r->is_file) {
  2445.       if (r->fp)
  2446.         fclose(r->fp);
  2447.       r->fp=NULL;
  2448.     } else {
  2449.       if (r->soc!=LOCAL_SOCKET_ID)
  2450.         deletesoc_r(r);
  2451.     }
  2452.     r->soc=INVALID_SOCKET;
  2453.   }
  2454. }
  2455.  
  2456. // free the addr buffer
  2457. // always returns 1
  2458. HTS_INLINE int deleteaddr(htsblk* r) {
  2459.   if (r->adr != NULL) {
  2460.     freet(r->adr);
  2461.     r->adr = NULL;
  2462.   }
  2463.   if (r->headers != NULL) {
  2464.     freet(r->headers);
  2465.     r->headers = NULL;
  2466.   }
  2467.   return 1;
  2468. }
  2469.  
  2470. // fermer une socket
  2471. HTS_INLINE void deletesoc(T_SOC soc) {
  2472.   if (soc!=INVALID_SOCKET && soc!=LOCAL_SOCKET_ID) {
  2473. #if HTS_WIDE_DEBUG    
  2474.     DEBUG_W("close %d\n" _ (int) soc);
  2475. #endif
  2476. #ifdef _WIN32
  2477.     closesocket(soc);
  2478. #else
  2479.     close(soc);
  2480. #endif
  2481. #if HTS_WIDE_DEBUG    
  2482.     DEBUG_W(".. done\n");
  2483. #endif
  2484.   }
  2485. }
  2486.  
  2487. /* Will also clean other things */
  2488. HTS_INLINE void deletesoc_r(htsblk* r) {
  2489. #if HTS_USEOPENSSL
  2490.   if (SSL_is_available && r->ssl_con) {
  2491.     SSL_shutdown(r->ssl_con);
  2492.     // SSL_CTX_set_quiet_shutdown(r->ssl_con->ctx, 1);
  2493.     SSL_free(r->ssl_con);
  2494.     r->ssl_con=NULL;
  2495.   }
  2496. #endif
  2497.   if (r->soc!=INVALID_SOCKET) {
  2498.     deletesoc(r->soc);
  2499.     r->soc=INVALID_SOCKET;
  2500.   }
  2501. }
  2502.  
  2503. // renvoi le nombre de secondes depuis 1970
  2504. HTS_INLINE TStamp time_local(void) {
  2505.   return ((TStamp) time(NULL));
  2506. }
  2507.  
  2508. // number of millisec since 1970
  2509. HTSEXT_API HTS_INLINE TStamp mtime_local(void) {
  2510. #ifndef HTS_DO_NOT_USE_FTIME
  2511.   struct timeb B;
  2512.   ftime( &B );
  2513.   return (TStamp) ( ((TStamp) B.time * (TStamp) 1000)
  2514.         + ((TStamp) B.millitm) );
  2515. #else
  2516.   // not precise..
  2517.   return (TStamp) ( ((TStamp) time_local() * (TStamp) 1000)
  2518.         + ((TStamp) 0) );
  2519. #endif
  2520. }
  2521.  
  2522. // convertit un nombre de secondes en temps (chaine)
  2523. void sec2str(char *st,TStamp t) {
  2524.   int j,h,m,s;
  2525.   
  2526.   j=(int) (t/(3600*24));
  2527.   t-=((TStamp) j)*(3600*24);
  2528.   h=(int) (t/(3600));
  2529.   t-=((TStamp) h)*3600;
  2530.   m=(int) (t/60);
  2531.   t-=((TStamp) m)*60;
  2532.   s=(int) t;
  2533.   
  2534.   if (j>0)
  2535.     sprintf(st,"%d days, %d hours %d minutes %d seconds",j,h,m,s);
  2536.   else if (h>0)
  2537.     sprintf(st,"%d hours %d minutes %d seconds",h,m,s);
  2538.   else if (m>0)
  2539.     sprintf(st,"%d minutes %d seconds",m,s);
  2540.   else
  2541.     sprintf(st,"%d seconds",s);
  2542. }
  2543.  
  2544. // idem, plus court (chaine)
  2545. HTSEXT_API void qsec2str(char *st,TStamp t) {
  2546.   int j,h,m,s;
  2547.   
  2548.   j=(int) (t/(3600*24));
  2549.   t-=((TStamp) j)*(3600*24);
  2550.   h=(int) (t/(3600));
  2551.   t-=((TStamp) h)*3600;
  2552.   m=(int) (t/60);
  2553.   t-=((TStamp) m)*60;
  2554.   s=(int) t;
  2555.   
  2556.   if (j>0)
  2557.     sprintf(st,"%dd,%02dh,%02dmin%02ds",j,h,m,s);
  2558.   else if (h>0)
  2559.     sprintf(st,"%dh,%02dmin%02ds",h,m,s);
  2560.   else if (m>0)
  2561.     sprintf(st,"%dmin%02ds",m,s);
  2562.   else
  2563.     sprintf(st,"%ds",s);
  2564. }
  2565.  
  2566.  
  2567. // heure actuelle, GMT, format rfc (taille buffer 256o)
  2568. void time_gmt_rfc822(char* s) {
  2569.   time_t tt;
  2570.   struct tm* A;
  2571.   tt=time(NULL);
  2572.   A=gmtime(&tt);
  2573.   if (A==NULL)
  2574.     A=localtime(&tt);
  2575.   time_rfc822(s,A);
  2576. }
  2577.  
  2578. // heure actuelle, format rfc (taille buffer 256o)
  2579. void time_local_rfc822(char* s) {
  2580.   time_t tt;
  2581.   struct tm* A;
  2582.   tt=time(NULL);
  2583.   A=localtime(&tt);
  2584.   time_rfc822_local(s,A);
  2585. }
  2586.  
  2587. /* convertir une chaine en temps */
  2588. struct tm* convert_time_rfc822(struct tm *result, const char* s) {
  2589.   char months[]="jan feb mar apr may jun jul aug sep oct nov dec";
  2590.   char str[256];
  2591.   char* a;
  2592.   /* */
  2593.   int result_mm=-1;
  2594.   int result_dd=-1;
  2595.   int result_n1=-1;
  2596.   int result_n2=-1;
  2597.   int result_n3=-1;
  2598.   int result_n4=-1;
  2599.   /* */
  2600.  
  2601.   if ((int) strlen(s) > 200)
  2602.     return NULL;
  2603.   strcpybuff(str,s);
  2604.   hts_lowcase(str);
  2605.   /* Θliminer :,- */
  2606.   while( (a=strchr(str,'-')) ) *a=' ';
  2607.   while( (a=strchr(str,':')) ) *a=' ';
  2608.   while( (a=strchr(str,',')) ) *a=' ';
  2609.   /* tokeniser */
  2610.   a=str;
  2611.   while(*a) {
  2612.     char *first,*last;
  2613.     char tok[256];
  2614.     /* dΘcouper mot */
  2615.     while(*a==' ') a++;   /* sauter espaces */
  2616.     first=a;
  2617.     while((*a) && (*a!=' ')) a++;
  2618.     last=a;
  2619.     tok[0]='\0';
  2620.     if (first!=last) {
  2621.       char* pos;
  2622.       strncatbuff(tok,first,(int) (last - first));
  2623.       /* analyser */
  2624.       if ( (pos=strstr(months,tok)) ) {               /* month always in letters */
  2625.         result_mm=((int) (pos - months))/4;
  2626.       } else {
  2627.         int number;
  2628.         if (sscanf(tok,"%d",&number) == 1) {      /* number token */
  2629.           if (result_dd<0)                        /* day always first number */
  2630.             result_dd=number;
  2631.           else if (result_n1<0)
  2632.             result_n1=number;
  2633.           else if (result_n2<0)
  2634.             result_n2=number;
  2635.           else if (result_n3<0)
  2636.             result_n3=number;
  2637.           else if (result_n4<0)
  2638.             result_n4=number;
  2639.         }   /* sinon, bruit de fond(+1GMT for exampel) */
  2640.       }
  2641.     }
  2642.   }
  2643.   if ((result_n1>=0) && (result_mm>=0) && (result_dd>=0) && (result_n2>=0) && (result_n3>=0) && (result_n4>=0)) {
  2644.     if (result_n4>=1000) {               /* Sun Nov  6 08:49:37 1994 */
  2645.       result->tm_year=result_n4-1900;
  2646.       result->tm_hour=result_n1;
  2647.       result->tm_min=result_n2;
  2648.       result->tm_sec=max(result_n3,0);
  2649.     } else {                            /* Sun, 06 Nov 1994 08:49:37 GMT or Sunday, 06-Nov-94 08:49:37 GMT */
  2650.       result->tm_hour=result_n2;
  2651.       result->tm_min=result_n3;
  2652.       result->tm_sec=max(result_n4,0);
  2653.       if (result_n1<=50)                /* 00 means 2000 */
  2654.         result->tm_year=result_n1+100;
  2655.       else if (result_n1<1000)          /* 99 means 1999 */
  2656.         result->tm_year=result_n1;
  2657.       else                              /* 2000 */
  2658.         result->tm_year=result_n1-1900;
  2659.     }
  2660.     result->tm_isdst=0;        /* assume GMT */
  2661.     result->tm_yday=-1;        /* don't know */
  2662.     result->tm_wday=-1;        /* don't know */
  2663.     result->tm_mon=result_mm;
  2664.     result->tm_mday=result_dd;
  2665.     return result;
  2666.   }
  2667.   return NULL;
  2668. }
  2669.  
  2670. static time_t getGMT(struct tm *tm) {        /* hey, time_t is local! */
  2671.     time_t t = mktime(tm);
  2672.     if (t != (time_t) -1 && t != (time_t) 0) {
  2673.     /* BSD does not have static "timezone" declared */
  2674. #if (defined(BSD) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD_kernel__))
  2675.     time_t now = time(NULL); 
  2676.     time_t timezone = - localtime(&now)->tm_gmtoff;
  2677. #endif
  2678.     return (time_t) (t - timezone);
  2679.     }
  2680.     return (time_t) -1;
  2681. }
  2682.  
  2683. /* sets file time. -1 if error */
  2684. int set_filetime(const char* file, struct tm* tm_time) {
  2685.     time_t t = getGMT(tm_time);
  2686.     if (t != (time_t) -1) {
  2687.       struct utimbuf tim;
  2688.         memset(&tim, 0, sizeof(tim));
  2689.       tim.actime = tim.modtime = t; 
  2690.         return utime(file, &tim);
  2691.     }
  2692.     return -1;
  2693. }
  2694.  
  2695. /* sets file time from RFC822 date+time, -1 if error*/
  2696. int set_filetime_rfc822(const char* file, const char* date) {
  2697.     struct tm buffer;
  2698.   struct tm* tm_s = convert_time_rfc822(&buffer, date);
  2699.   if (tm_s) {
  2700.     return set_filetime(file,tm_s);
  2701.   } else return -1;
  2702. }
  2703.  
  2704. int get_filetime_rfc822(const char* file, char* date) {
  2705.   struct stat buf;
  2706.   date[0] = '\0';
  2707.   if (stat(file, &buf) == 0) {
  2708.     struct tm* A;
  2709.     time_t tt = buf.st_mtime;
  2710.     A=gmtime(&tt);
  2711.     if (A==NULL)
  2712.       A=localtime(&tt);
  2713.     if (A != NULL) {
  2714.       time_rfc822(date, A);
  2715.       return 1;
  2716.     }
  2717.   }
  2718.   return 0;
  2719. }
  2720.  
  2721. // heure au format rfc (taille buffer 256o)
  2722. HTS_INLINE void time_rfc822(char* s,struct tm * A) {
  2723.   if (A == NULL) {
  2724.     int localtime_returned_null=0;
  2725.     assert(localtime_returned_null);
  2726.   }
  2727.   strftime(s,256,"%a, %d %b %Y %H:%M:%S GMT",A);
  2728. }
  2729.  
  2730. // heure locale au format rfc (taille buffer 256o)
  2731. HTS_INLINE void time_rfc822_local(char* s,struct tm * A) {
  2732.   if (A == NULL) {
  2733.     int localtime_returned_null=0;
  2734.     assert(localtime_returned_null);
  2735.   }
  2736.   strftime(s,256,"%a, %d %b %Y %H:%M:%S",A);
  2737. }
  2738.  
  2739. // conversion en b,Kb,Mb
  2740. HTSEXT_API char* int2bytes(strc_int2bytes2* strc, LLint n) {
  2741.   char** a = int2bytes2(strc, n);
  2742.   strcpybuff(strc->catbuff, a[0]);
  2743.   strcatbuff(strc->catbuff, a[1]);
  2744.   return strc->catbuff;
  2745. }
  2746.  
  2747. // conversion en b/s,Kb/s,Mb/s
  2748. HTSEXT_API char* int2bytessec(strc_int2bytes2* strc, long int n) {
  2749.     char buff[256];
  2750.   char** a = int2bytes2(strc, n);
  2751.   strcpybuff(buff, a[0]);
  2752.   strcatbuff(buff, a[1]);
  2753.   return concat(strc->catbuff, buff, "/s");
  2754. }
  2755. HTSEXT_API char* int2char(strc_int2bytes2* strc, int n) {
  2756.   sprintf(strc->buff2, "%d", n);
  2757.   return strc->buff2;
  2758. }
  2759.  
  2760. // conversion en b,Kb,Mb, nombre et type sΘparΘs
  2761. // limite: 2.10^9.10^6B
  2762.  
  2763. /* See http://physics.nist.gov/cuu/Units/binary.html */
  2764. #define ToLLint(a) ((LLint)(a))
  2765. #define ToLLintKiB (ToLLint(1024))
  2766. #define ToLLintMiB (ToLLintKiB*ToLLintKiB)
  2767. #ifdef HTS_LONGLONG
  2768. #define ToLLintGiB (ToLLintKiB*ToLLintKiB*ToLLintKiB)
  2769. #define ToLLintTiB (ToLLintKiB*ToLLintKiB*ToLLintKiB*ToLLintKiB)
  2770. #define ToLLintPiB (ToLLintKiB*ToLLintKiB*ToLLintKiB*ToLLintKiB*ToLLintKiB)
  2771. #endif
  2772. HTSEXT_API char** int2bytes2(strc_int2bytes2* strc, LLint n) {
  2773.   if (n < ToLLintKiB) {
  2774.     sprintf(strc->buff1,"%d",(int)(LLint)n);
  2775.     strcpybuff(strc->buff2,"B");
  2776.   } else if (n < ToLLintMiB) {
  2777.     sprintf(strc->buff1,"%d,%02d",(int)((LLint)(n/ToLLintKiB)),(int)((LLint)((n%ToLLintKiB)*100)/ToLLintKiB));
  2778.     strcpybuff(strc->buff2,"KiB");
  2779.   }
  2780. #ifdef HTS_LONGLONG
  2781.   else if (n < ToLLintGiB) {
  2782.     sprintf(strc->buff1,"%d,%02d",(int)((LLint)(n/(ToLLintMiB))),(int)((LLint)(((n%(ToLLintMiB))*100)/(ToLLintMiB))));
  2783.     strcpybuff(strc->buff2,"MiB");
  2784.   } else if (n < ToLLintTiB) {
  2785.     sprintf(strc->buff1,"%d,%02d",(int)((LLint)(n/(ToLLintGiB))),(int)((LLint)(((n%(ToLLintGiB))*100)/(ToLLintGiB))));
  2786.     strcpybuff(strc->buff2,"GiB");
  2787.   } else if (n < ToLLintPiB) {
  2788.     sprintf(strc->buff1,"%d,%02d",(int)((LLint)(n/(ToLLintTiB))),(int)((LLint)(((n%(ToLLintTiB))*100)/(ToLLintTiB))));
  2789.     strcpybuff(strc->buff2,"TiB");
  2790.   } else {
  2791.     sprintf(strc->buff1,"%d,%02d",(int)((LLint)(n/(ToLLintPiB))),(int)((LLint)(((n%(ToLLintPiB))*100)/(ToLLintPiB))));
  2792.     strcpybuff(strc->buff2,"PiB");
  2793.   }
  2794. #else
  2795.   else {
  2796.     sprintf(strc->buff1,"%d,%02d",(int)((LLint)(n/(ToLLintMiB))),(int)((LLint)(((n%(ToLLintMiB))*100)/(ToLLintMiB))));
  2797.     strcpybuff(strc->buff2,"MiB");
  2798.   }
  2799. #endif
  2800.   strc->buffadr[0]=strc->buff1;
  2801.   strc->buffadr[1]=strc->buff2;
  2802.   return strc->buffadr;
  2803. }
  2804.  
  2805. #ifdef _WIN32
  2806. #else
  2807. // ignore sigpipe?
  2808. int sig_ignore_flag( int setflag ) {     // flag ignore
  2809.   static int flag=0;   /* YES, this one is true static */
  2810.   if (setflag>=0)
  2811.     flag=setflag;
  2812.   return flag;
  2813. }
  2814. #endif
  2815.  
  2816. // envoi de texte (en tΩtes gΘnΘralement) sur la socket soc
  2817. HTS_INLINE int sendc(htsblk* r, const char* s) {
  2818.   int n, ssz = (int)strlen(s);
  2819.  
  2820. #ifdef _WIN32
  2821. #else
  2822.   sig_ignore_flag(1);
  2823. #endif
  2824. #if HDEBUG
  2825.   write(0,s,ssz);
  2826. #endif
  2827.  
  2828. #if HTS_USEOPENSSL
  2829.   if (SSL_is_available && r->ssl) {
  2830.     n = SSL_write(r->ssl_con, s, ssz);
  2831.   } else
  2832. #endif
  2833.     n = send(r->soc,s,ssz,0);
  2834.  
  2835. #ifdef _WIN32
  2836. #else
  2837.   sig_ignore_flag(0);
  2838. #endif
  2839.  
  2840.   return ( n == ssz ) ? n : -1;
  2841. }
  2842.  
  2843.  
  2844. // Remplace read
  2845. int finput(int fd,char* s,int max) {
  2846.   char c;
  2847.   int j=0;
  2848.   do {
  2849.     //c=fgetc(fp);
  2850.     if (read(fd,&c,1)<=0) {
  2851.       c=0;
  2852.     }
  2853.     if (c!=0) {
  2854.       switch(c) {
  2855.       case 10: c=0; break;
  2856.       case 13: break;  // sauter ces caractΦres
  2857.       default: s[j++]=c; break;
  2858.       }
  2859.     }
  2860.   }  while((c!=0) && (j<max-1));
  2861.   s[j]='\0';
  2862.   return j;
  2863.  
  2864. // Like linput, but in memory (optimized)
  2865. int binput(char* buff, char* s, int max) {
  2866.   int count = 0;
  2867.   int destCount = 0;
  2868.  
  2869.   // Note: \0 will return 1
  2870.   while(destCount < max && buff != NULL && buff[count] != '\0' && buff[count] != '\n') {
  2871.     if (buff[count] != '\r') {
  2872.       s[destCount++] = buff[count];
  2873.     }
  2874.     count++;
  2875.   }
  2876.   s[destCount] = '\0';
  2877.  
  2878.   // then return the supplemental jump offset
  2879.   return count + 1;
  2880.  
  2881. // Lecture d'une ligne (peut Ωtre unicode α priori)
  2882. int linput(FILE* fp,char* s,int max) {
  2883.   int c;
  2884.   int j=0;
  2885.   do {
  2886.     c=fgetc(fp);
  2887.     if (c!=EOF) {
  2888.       switch(c) {
  2889.         case 13: break;  // sauter CR
  2890.         case 10: c=-1; break;
  2891.         case 9: case 12: break;  // sauter ces caractΦres
  2892.         default: s[j++]=(char) c; break;
  2893.       }
  2894.     }
  2895.   }  while((c!=-1) && (c!=EOF) && (j<(max-1)));
  2896.   s[j]='\0';
  2897.   return j;
  2898. }
  2899. int linputsoc(T_SOC soc, char* s, int max) {
  2900.   int c;
  2901.   int j=0;
  2902.   do {
  2903.     unsigned char ch;
  2904.     if (recv(soc, &ch, 1, 0) == 1) {
  2905.       c = ch;
  2906.     } else {
  2907.       c = EOF;
  2908.     }
  2909.     if (c!=EOF) {
  2910.       switch(c) {
  2911.         case 13: break;  // sauter CR
  2912.         case 10: c=-1; break;
  2913.         case 9: case 12: break;  // sauter ces caractΦres
  2914.         default: s[j++]=(char) c; break;
  2915.       }
  2916.     }
  2917.   }  while((c!=-1) && (c!=EOF) && (j<(max-1)));
  2918.   s[j]='\0';
  2919.   return j;
  2920. }
  2921. int linputsoc_t(T_SOC soc, char* s, int max, int timeout) {
  2922.   if (check_readinput_t(soc, timeout)) {
  2923.     return linputsoc(soc, s, max);
  2924.   }
  2925.   return -1;
  2926. }
  2927. int linput_trim(FILE* fp,char* s,int max) {
  2928.   int rlen=0;
  2929.   char* ls=(char*) malloct(max+2);
  2930.   s[0]='\0';
  2931.   if (ls) {
  2932.     char* a;
  2933.     // lire ligne
  2934.     rlen=linput(fp,ls,max);
  2935.     if (rlen) {
  2936.       // sauter espaces et tabs en fin
  2937.       while( (rlen>0) && ((ls[max(rlen-1,0)]==' ') || (ls[max(rlen-1,0)]=='\t')) )
  2938.         ls[--rlen]='\0';
  2939.       // sauter espaces en dΘbut
  2940.       a=ls;
  2941.       while((rlen>0) && ((*a==' ') || (*a=='\t'))) {
  2942.         a++;
  2943.         rlen--;
  2944.       }
  2945.       if (rlen>0) {
  2946.         memcpy(s,a,rlen);      // can copy \0 chars
  2947.         s[rlen]='\0';
  2948.       }
  2949.     }
  2950.     //
  2951.     freet(ls);
  2952.   }
  2953.   return rlen;
  2954. }
  2955. int linput_cpp(FILE* fp,char* s,int max) {
  2956.   int rlen=0;
  2957.   s[0]='\0';
  2958.   do {
  2959.     int ret;
  2960.     if (rlen>0)
  2961.     if (s[rlen-1]=='\\')
  2962.       s[--rlen]='\0';      // couper \ final
  2963.     // lire ligne
  2964.     ret=linput_trim(fp,s+rlen,max-rlen);
  2965.     if (ret>0)
  2966.       rlen+=ret;
  2967.   } while((s[max(rlen-1,0)]=='\\') && (rlen<max));
  2968.   return rlen;
  2969. }
  2970.  
  2971. // idem avec les car spΘciaux
  2972. void rawlinput(FILE* fp,char* s,int max) {
  2973.   int c;
  2974.   int j=0;
  2975.   do {
  2976.     c=fgetc(fp);
  2977.     if (c!=EOF) {
  2978.       switch(c) {
  2979.         case 13: break;  // sauter CR
  2980.         case 10: c=-1; break;
  2981.         default: s[j++]=(char) c; break;
  2982.       }
  2983.     }
  2984.   }  while((c!=-1) && (c!=EOF) && (j<(max-1)));
  2985.   s[j++]='\0';
  2986. }
  2987.  
  2988. //cherche chaine, case insensitive
  2989. char* strstrcase(char *s,char *o) {
  2990.   while((*s) && (strfield(s,o)==0)) s++;
  2991.   if (*s=='\0') return NULL;
  2992.   return s;  
  2993. }
  2994.  
  2995.  
  2996. // Unicode detector
  2997. // See http://www.unicode.org/unicode/reports/tr28/
  2998. // (sect Table 3.1B. Legal UTF-8 Byte Sequences)
  2999. typedef struct {
  3000.   unsigned int pos;
  3001.   unsigned char data[4];
  3002. } t_auto_seq;
  3003.  
  3004. // char between a and b
  3005. #define CHAR_BETWEEN(c, a, b)       ( (c) >= 0x##a ) && ( (c) <= 0x##b )
  3006. // sequence start
  3007. #define SEQBEG                      ( inseq == 0 )
  3008. // in this block
  3009. #define BLK(n,a, b)                 ( (seq.pos >= n) && ((err = CHAR_BETWEEN(seq.data[n], a, b))) )
  3010. #define ELT(n,a)                    BLK(n,a,a)
  3011. // end
  3012. #define SEQEND                      ((ok = 1))
  3013. // sequence started, character will fail if error
  3014. #define IN_SEQ                      ( (inseq = 1) )
  3015. // decoding error
  3016. #define BAD_SEQ                     ( (ok == 0) && (inseq != 0) && (!err) )
  3017. // no sequence started
  3018. #define NO_SEQ                      ( inseq == 0 )
  3019.  
  3020. // is this block an UTF unicode textfile?
  3021. // 0 : no
  3022. // 1 : yes
  3023. // -1: don't know
  3024. int is_unicode_utf8(unsigned char* buffer, unsigned int size) {
  3025.   t_auto_seq seq;
  3026.   unsigned int i;
  3027.   int is_utf=-1;
  3028.  
  3029.   seq.pos=0;
  3030.   for(i=0 ; i < size ; i++) {
  3031.     unsigned int ok=0;
  3032.     unsigned int inseq=0;
  3033.     unsigned int err=0;
  3034.  
  3035.     seq.data[seq.pos]=buffer[i];
  3036.     /**/ if ( SEQBEG && BLK(0,00,7F) && IN_SEQ && SEQEND                                                 ) { }
  3037.     else if ( SEQBEG && BLK(0,C2,DF) && IN_SEQ && BLK(1,80,BF) && SEQEND                                 ) { }
  3038.     else if ( SEQBEG && ELT(0,E0   ) && IN_SEQ && BLK(1,A0,BF) && BLK(2,80,BF) && SEQEND                 ) { }
  3039.     else if ( SEQBEG && BLK(0,E1,EC) && IN_SEQ && BLK(1,80,BF) && BLK(2,80,BF) && SEQEND                 ) { }
  3040.     else if ( SEQBEG && ELT(0,ED   ) && IN_SEQ && BLK(1,80,9F) && BLK(2,80,BF) && SEQEND                 ) { }
  3041.     else if ( SEQBEG && BLK(0,EE,EF) && IN_SEQ && BLK(1,80,BF) && BLK(2,80,BF) && SEQEND                 ) { }
  3042.     else if ( SEQBEG && ELT(0,F0   ) && IN_SEQ && BLK(1,90,BF) && BLK(2,80,BF) && BLK(3,80,BF) && SEQEND ) { }
  3043.     else if ( SEQBEG && BLK(0,F1,F3) && IN_SEQ && BLK(1,80,BF) && BLK(2,80,BF) && BLK(3,80,BF) && SEQEND ) { }
  3044.     else if ( SEQBEG && ELT(0,F4   ) && IN_SEQ && BLK(1,80,8F) && BLK(2,80,BF) && BLK(3,80,BF) && SEQEND ) { }
  3045.     else if ( NO_SEQ ) {    // bad, unknown
  3046.       return 0;
  3047.     }
  3048.     /* */
  3049.     
  3050.     /* Error */
  3051.     if ( BAD_SEQ ) {
  3052.       return 0;
  3053.     }
  3054.  
  3055.     /* unicode character */
  3056.     if (seq.pos > 0)
  3057.       is_utf=1;
  3058.  
  3059.     /* Next */
  3060.     if (ok)
  3061.       seq.pos=0;
  3062.     else
  3063.       seq.pos++;
  3064.  
  3065.     /* Internal error */
  3066.     if (seq.pos >= 4)
  3067.       return 0;
  3068.  
  3069.   }
  3070.  
  3071.   return is_utf;
  3072. }
  3073.  
  3074. void map_characters(unsigned char* buffer, unsigned int size, unsigned int* map) {
  3075.   unsigned int i;
  3076.   memset(map, 0, sizeof(unsigned int) * 256);
  3077.   for(i = 0 ; i < size ; i++) {
  3078.     map[buffer[i]]++;
  3079.   }
  3080. }
  3081.  
  3082.  
  3083. // le fichier est-il un fichier html?
  3084. //  0 : non
  3085. //  1 : oui
  3086. // -1 : on sait pas
  3087. // -2 : on sait pas, pas d'extension
  3088. int ishtml(httrackp *opt,const char* fil) {
  3089.   /* User-defined MIME types (overrides ishtml()) */
  3090.   char BIGSTK fil_noquery[HTS_URLMAXSIZE*2];
  3091.   char mime[256];
  3092.   char* a;
  3093.   strcpybuff(fil_noquery, fil);
  3094.   if ((a = strchr(fil_noquery, '?')) != NULL) {
  3095.     *a = '\0';
  3096.   }
  3097.   if (get_userhttptype(opt, mime, fil_noquery)) {
  3098.     if (strfield2(mime, "text/html")) {
  3099.       return 1;
  3100.     } else {
  3101.       return 0;
  3102.     }
  3103.   }
  3104.  
  3105.   /* Search for known ext */
  3106.   for (a = fil_noquery + strlen(fil_noquery) - 1 ; (*a!='.') && (*a!='/')  && ( a > fil_noquery ) ; a-- );
  3107.   if (*a == '.') {  // a une extension
  3108.     char BIGSTK fil_noquery[HTS_URLMAXSIZE*2];
  3109.     char* b;
  3110.     int ret;
  3111.     char* dotted = a;
  3112.     fil_noquery[0]='\0';
  3113.     a++;  // pointer sur extension
  3114.     strncatbuff(fil_noquery,a,HTS_URLMAXSIZE);
  3115.     b=strchr(fil_noquery,'?');
  3116.     if (b)
  3117.       *b='\0';
  3118.     ret = ishtml_ext(fil_noquery);     // retour
  3119.     if (ret == -1) {
  3120.       switch(is_knowntype(opt,dotted)) {
  3121.       case 1:
  3122.         ret = 0;     // connu, non html
  3123.         break;
  3124.       case 2:
  3125.         ret = 1;     // connu, html
  3126.         break;
  3127.       default:
  3128.         ret = -1;    // inconnu..
  3129.         break;
  3130.       }
  3131.     }
  3132.     return ret;
  3133.   } else return -2;   // indΘterminΘ, par exemple /truc
  3134. }
  3135.  
  3136. // idem, mais pour uniquement l'extension
  3137. int ishtml_ext(const char* a) {
  3138.   int html=0;  
  3139.   //
  3140.   if (strfield2(a,"html"))       html = 1;
  3141.   else if (strfield2(a,"htm"))   html = 1;
  3142.   else if (strfield2(a,"shtml")) html = 1;
  3143.   else if (strfield2(a,"phtml")) html = 1;
  3144.   else if (strfield2(a,"htmlx")) html = 1;
  3145.   else if (strfield2(a,"shtm"))  html = 1;
  3146.   else if (strfield2(a,"phtm"))  html = 1;
  3147.   else if (strfield2(a,"htmx"))  html = 1;
  3148.   //
  3149.   // insuccΦs..
  3150.   else {
  3151. #if 1
  3152.     html = -1;    // inconnu..
  3153. #else
  3154.     // XXXXXX not suitable (ext)
  3155.     switch(is_knownext(a)) {
  3156.     case 1:
  3157.       html = 0;     // connu, non html
  3158.       break;
  3159.     case 2:
  3160.       html = 1;     // connu, html
  3161.       break;
  3162.     default:
  3163.       html = -1;    // inconnu..
  3164.       break;
  3165.     }
  3166. #endif
  3167.   }
  3168.   return html;  
  3169. }
  3170.  
  3171. // error (404,500..)
  3172. HTS_INLINE int ishttperror(int err) {
  3173.   switch (err/100) {
  3174.     case 4: case 5: return 1;
  3175.       break;
  3176.   }
  3177.   return 0;
  3178. }
  3179.  
  3180.  
  3181. // retourne le pointeur ou le pointeur + offset si il existe dans la chaine un @ signifiant 
  3182. // une identification
  3183. HTSEXT_API char* jump_identification(const char* source) {
  3184.   const char *a,*trytofind;
  3185.   if (strcmp(source, "file://") == 0)
  3186.       return (char*) source;
  3187.   // rechercher dernier @ (car parfois email transmise dans adresse!)
  3188.   // mais sauter ftp:// Θventuel
  3189.   a = jump_protocol(source);
  3190.   trytofind = strrchr_limit(a, '@', strchr(a,'/'));
  3191.   return (char*) ( (trytofind != NULL) ? trytofind : a );
  3192. }
  3193.  
  3194. HTSEXT_API char* jump_normalized(const char* source) {
  3195.   if (strcmp(source, "file://") == 0)
  3196.       return (char*) source;
  3197.   source = jump_identification(source); 
  3198.   if (strfield(source, "www") && source[3] != '\0') {
  3199.     if (source[3] == '.') {       // www.foo.com -> foo.com
  3200.       source += 4;  
  3201.     } else {                      // www-4.foo.com -> foo.com
  3202.       const char* a = source + 3;
  3203.       while(*a && ( isdigit(*a) || *a == '-') ) a++;
  3204.       if (*a == '.') {
  3205.         source = a + 1;
  3206.       }
  3207.     }
  3208.   }
  3209.   return (char*) source;  
  3210. }
  3211.  
  3212. static int sortNormFnc(const void * a_, const void * b_) {
  3213.   char** a = (char**) a_;
  3214.   char** b = (char**) b_;
  3215.   return strcmp(*a+1, *b+1);
  3216. }
  3217.  
  3218.  
  3219. HTSEXT_API char* fil_normalized(const char* source, char* dest) {
  3220.   char lastc = 0;
  3221.   int gotquery=0;
  3222.   int ampargs=0;
  3223.   int i,j;
  3224.   char* query=NULL;
  3225.   for(i=j=0 ; source[i] != '\0'; i++) {
  3226.     if (!gotquery && source[i] == '?')
  3227.       gotquery=ampargs=1;
  3228.     if ( 
  3229.       (!gotquery && lastc == '/' && source[i] == '/')  // foo//bar -> foo/bar
  3230.       ) {
  3231.     }
  3232.     else {
  3233.       if (gotquery && source[i] == '&') {
  3234.         ampargs++;
  3235.       }
  3236.       dest[j++] = source[i];
  3237.     }
  3238.     lastc = source[i];
  3239.   }
  3240.   dest[j++] = '\0';
  3241.  
  3242.   /* Sort arguments (&foo=1&bar=2 == &bar=2&foo=1) */
  3243.   if (ampargs > 1) {
  3244.     char** amps = malloct(ampargs * sizeof(char*));
  3245.     char* copyBuff = NULL;
  3246.     int qLen=0;
  3247.     assertf(amps != NULL);
  3248.     gotquery = 0;
  3249.     for(i=j=0 ; dest[i] != '\0'; i++) {
  3250.       if ( (gotquery && dest[i] == '&') || ( !gotquery && dest[i] == '?') ) {
  3251.         if (!gotquery) {
  3252.           gotquery=1;
  3253.           query = &dest[i];
  3254.           qLen = (int)strlen(query);
  3255.         }
  3256.         assertf(j < ampargs);
  3257.         amps[j++] = &dest[i];
  3258.         dest[i] = '\0';
  3259.       }
  3260.     }
  3261.     assertf(j == ampargs);
  3262.  
  3263.     /* Sort 'em all */
  3264.     qsort(amps, ampargs, sizeof(char*), sortNormFnc);
  3265.  
  3266.     /* Replace query by sorted query */
  3267.     copyBuff = malloct(qLen + 1);
  3268.     assertf(copyBuff != NULL);
  3269.     copyBuff[0] = '\0';
  3270.     for(i = 0 ; i < ampargs ; i++) {
  3271.       if (i == 0)
  3272.         strcatbuff(copyBuff, "?");
  3273.       else
  3274.         strcatbuff(copyBuff, "&");
  3275.       strcatbuff(copyBuff, amps[i] + 1);
  3276.     }
  3277.     assert((int)strlen(copyBuff) <= qLen);
  3278.     strcpybuff(query, copyBuff);
  3279.  
  3280.     /* Cleanup */
  3281.     freet(amps);
  3282.     freet(copyBuff);
  3283.   }
  3284.   
  3285.   return dest;
  3286. }
  3287.  
  3288. #define endwith(a) ( (len >= (sizeof(a)-1)) ? ( strncmp(dest, a+len-(sizeof(a)-1), sizeof(a)-1) == 0 ) : 0 );
  3289. HTSEXT_API char* adr_normalized(const char* source, char* dest) {
  3290.   /* not yet too aggressive (no com<->net<->org checkings) */
  3291.   strcpybuff(dest, jump_normalized(source));
  3292.   return dest;
  3293. }
  3294. #undef endwith
  3295.  
  3296.  
  3297. // find port (:80) or NULL if not found
  3298. // can handle IPV6 addresses
  3299. HTSEXT_API char* jump_toport(const char* source) {
  3300.   const char *a,*trytofind;
  3301.   a = jump_identification(source);
  3302.   trytofind = strrchr_limit(a, ']', strchr(source, '/'));    // find last ] (http://[3ffe:b80:1234::1]:80/foo.html)
  3303.   a = strchr( (trytofind)?trytofind:a, ':');
  3304.   return (char*)a;
  3305. }
  3306.  
  3307. // strrchr, but not too far
  3308. char* strrchr_limit(const char* s, char c, const char* limit) {
  3309.   if (limit == NULL) {
  3310.     const char* p = strrchr(s, c);
  3311.     return (char*) ( p ? (p+1) : NULL );
  3312.   } else {
  3313.     const char *a = NULL, *p;
  3314.     for(;;) {
  3315.       p = strchr( (a) ? a : s, c);
  3316.       if ((p >= limit) || (p == NULL))
  3317.         return (char*) a;
  3318.       a=p+1;
  3319.     }
  3320.   }
  3321. }
  3322.  
  3323. // strrchr, but not too far
  3324. char* strstr_limit(const char* s, const char* sub, const char* limit) {
  3325.   if (limit == NULL) {
  3326.     return strstr(s, sub);
  3327.   } else {
  3328.     const char* pos = strstr(s, sub);
  3329.     if (pos != NULL) {
  3330.       const char* farpos = strstr(s, limit);
  3331.       if (farpos == NULL || pos < farpos)
  3332.         return (char*) pos;
  3333.     }
  3334.   }
  3335.   return NULL;
  3336. }
  3337.  
  3338. // retourner adr sans ftp://
  3339. HTS_INLINE char* jump_protocol(const char* source) {
  3340.   int p;
  3341.   // scheme
  3342.   // "Comparisons of scheme names MUST be case-insensitive" (RFC2616)
  3343.   if ((p=strfield(source,"http:")))
  3344.     source+=p;
  3345.   else if ((p=strfield(source,"ftp:")))
  3346.     source+=p;
  3347.   else if ((p=strfield(source,"https:")))
  3348.     source+=p;
  3349.   else if ((p=strfield(source,"file:")))
  3350.     source+=p;
  3351. #if HTS_USEMMS
  3352.   else if ((p=strfield(source,"mms:")))
  3353.     source+=p;
  3354. #endif
  3355.   // net_path
  3356.   if (strncmp(source,"//",2)==0)
  3357.     source+=2;
  3358.   return (char*) source;
  3359. }
  3360.  
  3361. // codage base 64 a vers b
  3362. void code64(unsigned char* a,int size_a,unsigned char* b,int crlf) {
  3363.   int i1=0,i2=0,i3=0,i4=0;
  3364.   int loop=0;
  3365.   unsigned long int store;
  3366.   int n;
  3367.   const char _hts_base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3368.   while(size_a-- > 0) {  
  3369.     // 24 bits
  3370.     n=1; 
  3371.     store = *a++;
  3372.     if (size_a-- > 0) { n=2; store <<= 8; store |= *a++; }
  3373.     if (size_a-- > 0) { n=3; store <<= 8; store |= *a++; }
  3374.     if (n==3) {
  3375.       i4=store & 63;
  3376.       i3=(store>>6) & 63;
  3377.       i2=(store>>12) & 63;
  3378.       i1=(store>>18) & 63;
  3379.     } else if (n==2) {
  3380.       store<<=2;    
  3381.       i3=store & 63;
  3382.       i2=(store>>6) & 63;
  3383.       i1=(store>>12) & 63;
  3384.     } else {
  3385.       store<<=4;
  3386.       i2=store & 63;
  3387.       i1=(store>>6) & 63;
  3388.     }
  3389.     
  3390.     *b++ = _hts_base64[i1];
  3391.     *b++ = _hts_base64[i2];
  3392.     if (n>=2)
  3393.       *b++ = _hts_base64[i3];
  3394.     else
  3395.       *b++ = '=';
  3396.     if (n>=3)
  3397.       *b++ = _hts_base64[i4];
  3398.     else
  3399.       *b++ = '=';
  3400.  
  3401.     if (crlf && ( ( loop += 3 ) % 60) == 0 ) {
  3402.       *b++ = '\r';
  3403.       *b++ = '\n';
  3404.     }
  3405.   }
  3406.   *b++='\0';
  3407. }
  3408.  
  3409. // remplacer " par " etc..
  3410. // buffer MAX 1Ko
  3411. #define strcmpbeg(a, b) strncmp(a, b, strlen(b))
  3412. HTSEXT_API void unescape_amp(char* s) {
  3413.   while(*s) {
  3414.     if (*s=='&') {
  3415.       char* end=strchr(s,';');
  3416.       if ( end && (((int) (end - s)) <= 8) ) {
  3417.         unsigned char c=0;
  3418.         
  3419.         // http://www.w3.org/TR/xhtml-modularization/dtd_module_defs.html
  3420.         if (strcmpbeg(s, "&#") == 0) {
  3421.           int num=0;
  3422.           if ( (s[2] == 'x') || (s[2] == 'X')) {
  3423.             if (sscanf(s+3, "%x", &num) == 1 && num <= 0xff) {
  3424.               c=(unsigned char) num;
  3425.             }
  3426.           } else {
  3427.             if (sscanf(s+2, "%d", &num) == 1 && num <= 0xff) {
  3428.               c=(unsigned char) num;
  3429.             }
  3430.           }
  3431.         }
  3432.         else if (strcmpbeg(s, " ")==0)
  3433.           c=32; // hack - c=160;
  3434.         else if (strcmpbeg(s, "¡")==0)
  3435.           c=161;
  3436.         else if (strcmpbeg(s, "¢")==0)
  3437.           c=162;
  3438.         else if (strcmpbeg(s, "£")==0)
  3439.           c=163;
  3440.         else if (strcmpbeg(s, "¤")==0)
  3441.           c=164;
  3442.         else if (strcmpbeg(s, "¥")==0)
  3443.           c=165;
  3444.         else if (strcmpbeg(s, "¦")==0)
  3445.           c=166;
  3446.         else if (strcmpbeg(s, "§")==0)
  3447.           c=167;
  3448.         else if (strcmpbeg(s, "¨")==0)
  3449.           c=168;
  3450.         else if (strcmpbeg(s, "©")==0)
  3451.           c=169;
  3452.         else if (strcmpbeg(s, "ª")==0)
  3453.           c=170;
  3454.         //else if (strcmpbeg(s, "«")==0)
  3455.         //  c=171;
  3456.         else if (strcmpbeg(s, "¬")==0)
  3457.           c=172;
  3458.         //else if (strcmpbeg(s, "­")==0)
  3459.         //  c=173;
  3460.         else if (strcmpbeg(s, "®")==0)
  3461.           c=174;
  3462.         else if (strcmpbeg(s, "¯")==0)
  3463.           c=175;
  3464.         else if (strcmpbeg(s, "°")==0)
  3465.           c=176;
  3466.         else if (strcmpbeg(s, "±")==0)
  3467.           c=177;
  3468.         else if (strcmpbeg(s, "²")==0)
  3469.           c=178;
  3470.         else if (strcmpbeg(s, "³")==0)
  3471.           c=179;
  3472.         else if (strcmpbeg(s, "´")==0)
  3473.           c=180;
  3474.         else if (strcmpbeg(s, "µ")==0)
  3475.           c=181;
  3476.         else if (strcmpbeg(s, "¶")==0)
  3477.           c=182;
  3478.         else if (strcmpbeg(s, "·")==0)
  3479.           c=183;
  3480.         else if (strcmpbeg(s, "¸")==0)
  3481.           c=184;
  3482.         else if (strcmpbeg(s, "¹")==0)
  3483.           c=185;
  3484.         else if (strcmpbeg(s, "º")==0)
  3485.           c=186;
  3486.         //else if (strcmpbeg(s, "»")==0)
  3487.         //  c=187;
  3488.         else if (strcmpbeg(s, "¼")==0)
  3489.           c=188;
  3490.         else if (strcmpbeg(s, "½")==0)
  3491.           c=189;
  3492.         else if (strcmpbeg(s, "¾")==0)
  3493.           c=190;
  3494.         else if (strcmpbeg(s, "¿")==0)
  3495.           c=191;
  3496.         else if (strcmpbeg(s, "À")==0)
  3497.           c=192;
  3498.         else if (strcmpbeg(s, "Á")==0)
  3499.           c=193;
  3500.         else if (strcmpbeg(s, "Â")==0)
  3501.           c=194;
  3502.         else if (strcmpbeg(s, "Ã")==0)
  3503.           c=195;
  3504.         else if (strcmpbeg(s, "Ä")==0)
  3505.           c=196;
  3506.         else if (strcmpbeg(s, "Å")==0)
  3507.           c=197;
  3508.         else if (strcmpbeg(s, "Æ")==0)
  3509.           c=198;
  3510.         else if (strcmpbeg(s, "Ç")==0)
  3511.           c=199;
  3512.         else if (strcmpbeg(s, "È")==0)
  3513.           c=200;
  3514.         else if (strcmpbeg(s, "É")==0)
  3515.           c=201;
  3516.         else if (strcmpbeg(s, "Ê")==0)
  3517.           c=202;
  3518.         else if (strcmpbeg(s, "Ë")==0)
  3519.           c=203;
  3520.         else if (strcmpbeg(s, "Ì")==0)
  3521.           c=204;
  3522.         else if (strcmpbeg(s, "Í")==0)
  3523.           c=205;
  3524.         else if (strcmpbeg(s, "Î")==0)
  3525.           c=206;
  3526.         else if (strcmpbeg(s, "Ï")==0)
  3527.           c=207;
  3528.         else if (strcmpbeg(s, "Ð")==0)
  3529.           c=208;
  3530.         else if (strcmpbeg(s, "Ñ")==0)
  3531.           c=209;
  3532.         else if (strcmpbeg(s, "Ò")==0)
  3533.           c=210;
  3534.         else if (strcmpbeg(s, "Ó")==0)
  3535.           c=211;
  3536.         else if (strcmpbeg(s, "Ô")==0)
  3537.           c=212;
  3538.         else if (strcmpbeg(s, "Õ")==0)
  3539.           c=213;
  3540.         else if (strcmpbeg(s, "Ö")==0)
  3541.           c=214;
  3542.         else if (strcmpbeg(s, "×")==0)
  3543.           c=215;
  3544.         else if (strcmpbeg(s, "Ø")==0)
  3545.           c=216;
  3546.         else if (strcmpbeg(s, "Ù")==0)
  3547.           c=217;
  3548.         else if (strcmpbeg(s, "Ú")==0)
  3549.           c=218;
  3550.         else if (strcmpbeg(s, "Û")==0)
  3551.           c=219;
  3552.         else if (strcmpbeg(s, "Ü")==0)
  3553.           c=220;
  3554.         else if (strcmpbeg(s, "Ý")==0)
  3555.           c=221;
  3556.         else if (strcmpbeg(s, "Þ")==0)
  3557.           c=222;
  3558.         else if (strcmpbeg(s, "ß")==0)
  3559.           c=223;
  3560.         else if (strcmpbeg(s, "à")==0)
  3561.           c=224;
  3562.         else if (strcmpbeg(s, "á")==0)
  3563.           c=225;
  3564.         else if (strcmpbeg(s, "â")==0)
  3565.           c=226;
  3566.         else if (strcmpbeg(s, "ã")==0)
  3567.           c=227;
  3568.         else if (strcmpbeg(s, "ä")==0)
  3569.           c=228;
  3570.         else if (strcmpbeg(s, "å")==0)
  3571.           c=229;
  3572.         else if (strcmpbeg(s, "æ")==0)
  3573.           c=230;
  3574.         else if (strcmpbeg(s, "ç")==0)
  3575.           c=231;
  3576.         else if (strcmpbeg(s, "è")==0)
  3577.           c=232;
  3578.         else if (strcmpbeg(s, "é")==0)
  3579.           c=233;
  3580.         else if (strcmpbeg(s, "ê")==0)
  3581.           c=234;
  3582.         else if (strcmpbeg(s, "ë")==0)
  3583.           c=235;
  3584.         else if (strcmpbeg(s, "ì")==0)
  3585.           c=236;
  3586.         else if (strcmpbeg(s, "í")==0)
  3587.           c=237;
  3588.         else if (strcmpbeg(s, "î")==0)
  3589.           c=238;
  3590.         else if (strcmpbeg(s, "ï")==0)
  3591.           c=239;
  3592.         else if (strcmpbeg(s, "ð")==0)
  3593.           c=240;
  3594.         else if (strcmpbeg(s, "ñ")==0)
  3595.           c=241;
  3596.         else if (strcmpbeg(s, "ò")==0)
  3597.           c=242;
  3598.         else if (strcmpbeg(s, "ó")==0)
  3599.           c=243;
  3600.         else if (strcmpbeg(s, "ô")==0)
  3601.           c=244;
  3602.         else if (strcmpbeg(s, "õ")==0)
  3603.           c=245;
  3604.         else if (strcmpbeg(s, "ö")==0)
  3605.           c=246;
  3606.         else if (strcmpbeg(s, "÷")==0)
  3607.           c=247;
  3608.         else if (strcmpbeg(s, "ø")==0)
  3609.           c=248;
  3610.         else if (strcmpbeg(s, "ù")==0)
  3611.           c=249;
  3612.         else if (strcmpbeg(s, "ú")==0)
  3613.           c=250;
  3614.         else if (strcmpbeg(s, "û")==0)
  3615.           c=251;
  3616.         else if (strcmpbeg(s, "ü")==0)
  3617.           c=252;
  3618.         else if (strcmpbeg(s, "ý")==0)
  3619.           c=253;
  3620.         else if (strcmpbeg(s, "þ")==0)
  3621.           c=254;
  3622.         else if (strcmpbeg(s, "ÿ")==0)
  3623.           c=255;
  3624.         //        
  3625.         else if (strcmpbeg(s,"&")==0)
  3626.           c='&';
  3627.         else if (strcmpbeg(s,">")==0)
  3628.           c='>';
  3629.         else if (strcmpbeg(s,"«")==0)
  3630.           c='\"';
  3631.         else if (strcmpbeg(s,"<")==0)
  3632.           c='<';
  3633.         else if (strcmpbeg(s," ")==0)
  3634.           c=' ';
  3635.         else if (strcmpbeg(s,""")==0)
  3636.           c='\"';
  3637.         else if (strcmpbeg(s,"»")==0)
  3638.           c='\"';
  3639.         else if (strcmpbeg(s,"­")==0)
  3640.           c='-';
  3641.         else if (strcmpbeg(s,"˜")==0)
  3642.           c='~';
  3643.         // remplacer?
  3644.         if (c) {
  3645.           char BIGSTK buff[HTS_URLMAXSIZE*2];
  3646.           buff[0]=(char) c;
  3647.           strcpybuff(buff+1,end+1);
  3648.           strcpybuff(s,buff);
  3649.         }
  3650.       }
  3651.     }
  3652.     s++;
  3653.   }
  3654. }
  3655.  
  3656. static int ehexh(char c) {
  3657.   if ((c>='0') && (c<='9')) return c-'0';
  3658.   if ((c>='a') && (c<='f')) c-=('a'-'A');
  3659.   if ((c>='A') && (c<='F')) return (c-'A'+10);
  3660.   return 0;
  3661. }
  3662.  
  3663. static int ehex(const char* s) {
  3664.   return 16*ehexh(*s)+ehexh(*(s+1));
  3665. }
  3666.  
  3667. // remplacer %20 par ' ', | par : etc..
  3668. // buffer MAX 1Ko
  3669. HTSEXT_API char* unescape_http(char *catbuff, const char* s) {
  3670.   int i,j=0;
  3671.   for (i=0;i<(int) strlen(s);i++) {
  3672.     if (s[i]=='%') {
  3673.       i++;
  3674.       catbuff[j++]=(char) ehex(s+i);
  3675.       i++;    // sauter 2 caractΦres finalement
  3676.     }
  3677.     /*
  3678.     NON a cause de trucs comme /home/0,1837,1|7|1173|Content,00.html
  3679.     else if (s[i]=='|') {                     // exemple: file:///C|Program%20Files...
  3680.       tempo[j++]=':';
  3681.     }
  3682.     */
  3683.     else
  3684.       catbuff[j++]=s[i];
  3685.   }
  3686.   catbuff[j++]='\0';
  3687.   return catbuff;
  3688. }
  3689.  
  3690. // unescape in URL/URI ONLY what has to be escaped, to form a standard URL/URI
  3691. // DOES NOT DECODE %25
  3692. HTSEXT_API char* unescape_http_unharm(char *catbuff, const char* s, int no_high) {
  3693.   int i,j=0;
  3694.   for (i=0;i<(int) strlen(s);i++) {
  3695.     if (s[i]=='%') {
  3696.       int nchar=(char) ehex(s+i+1);
  3697.  
  3698.       int test = (  CHAR_RESERVED(nchar)
  3699.                 || ( nchar != '%' && CHAR_DELIM(nchar) )
  3700.                 || CHAR_UNWISE(nchar)
  3701.                 || CHAR_LOW(nchar)        /* CHAR_SPECIAL */
  3702.                 || CHAR_XXAVOID(nchar) 
  3703.                 || (
  3704.                   (no_high)
  3705.                   &&
  3706.                   CHAR_HIG(nchar)
  3707.                 )
  3708.                 );
  3709.  
  3710.       if (!test) {
  3711.         catbuff[j++]=(char) ehex(s+i+1);
  3712.         i+=2;
  3713.       } else {
  3714.         catbuff[j++]='%';
  3715.       }
  3716.     }
  3717.     /*
  3718.     NON a cause de trucs comme /home/0,1837,1|7|1173|Content,00.html
  3719.     else if (s[i]=='|') {                     // exemple: file:///C|Program%20Files...
  3720.       tempo[j++]=':';
  3721.     }
  3722.     */
  3723.     else
  3724.       catbuff[j++]=s[i];
  3725.   }
  3726.   catbuff[j++]='\0';
  3727.   return catbuff;
  3728. }
  3729.  
  3730. // remplacer " par %xx etc..
  3731. // buffer MAX 1Ko
  3732. HTSEXT_API void escape_spc_url(char* s) {
  3733.   x_escape_http(s,2);
  3734. }
  3735. // smith / john -> smith%20%2f%20john
  3736. HTSEXT_API void escape_in_url(char* s) {
  3737.   x_escape_http(s,1);
  3738. }
  3739. // smith / john -> smith%20/%20john
  3740. HTSEXT_API void escape_uri(char* s) {
  3741.   x_escape_http(s,3);
  3742. }
  3743. HTSEXT_API void escape_uri_utf(char* s) {
  3744.   x_escape_http(s,30);
  3745. }
  3746. HTSEXT_API void escape_check_url(char* s) {
  3747.   x_escape_http(s,0);
  3748. }
  3749. // same as escape_check_url, but returns char*
  3750. HTSEXT_API char* escape_check_url_addr(char *catbuff, const char* s) {
  3751.   char* adr;
  3752.   escape_check_url(adr = concat(catbuff, s, ""));
  3753.   return adr;
  3754. }
  3755.  
  3756. // strip all control characters
  3757. HTSEXT_API void escape_remove_control(char* s) {
  3758.   unsigned char* ss = (unsigned char*) s;
  3759.   while(*ss) {
  3760.     if (*ss < 32) {    /* CONTROL characters go away! */
  3761.       char BIGSTK tmp[HTS_URLMAXSIZE*2];
  3762.       strcpybuff(tmp, ss+1);
  3763.       strcpybuff(ss, tmp);
  3764.     } else {
  3765.       ss++;
  3766.     }
  3767.   }
  3768. }
  3769.  
  3770. HTSEXT_API void x_escape_html(char* s) {
  3771.   while(*s) {
  3772.     int test=0;
  3773.       test = (
  3774.                 CHAR_HIG(*s)
  3775.              || CHAR_XXAVOID(*s) );
  3776.  
  3777.     if (test) {
  3778.       char BIGSTK buffer[HTS_URLMAXSIZE*3];
  3779.       int n;
  3780.       n = (int)(unsigned char) *s;
  3781.       strcpybuff(buffer, s+1);
  3782.       sprintf(s,"&#x%02x;", n);
  3783.       strcatbuff(s, buffer);
  3784.     }
  3785.     s++;
  3786.   }
  3787. }
  3788.  
  3789.  
  3790. HTSEXT_API void x_escape_http(char* s,int mode) {
  3791.   while(*s) {
  3792.     int test=0;
  3793.     if (mode == 0)
  3794.       test=(strchr("\" ",*s)!=0);
  3795.     else if (mode==1) {
  3796.       test = (  CHAR_RESERVED(*s)
  3797.              || CHAR_DELIM(*s)
  3798.              || CHAR_UNWISE(*s)
  3799.              || CHAR_SPECIAL(*s)
  3800.              || CHAR_XXAVOID(*s)
  3801.              || CHAR_MARK(*s));
  3802.     }
  3803.     else if (mode==2)
  3804.       test=(*s == ' ');           // n'escaper que espace
  3805.     else if (mode==3) {                   // Θchapper que ce qui est nΘcessaire
  3806.       test = (
  3807.                 CHAR_SPECIAL(*s)
  3808.              || CHAR_XXAVOID(*s) );
  3809.     }
  3810.     else if (mode==30) {                   // Θchapper que ce qui est nΘcessaire
  3811.       test = (
  3812.                 CHAR_LOW(*s)
  3813.              || CHAR_XXAVOID(*s) );
  3814.     }
  3815.  
  3816.     if (test) {
  3817.       char BIGSTK buffer[HTS_URLMAXSIZE*3];
  3818.       int n;
  3819.       n=(int)(unsigned char) *s;
  3820.       strcpybuff(buffer,s+1);
  3821.       sprintf(s,"%%%02x",n);
  3822.       strcatbuff(s,buffer);
  3823.     }
  3824.     s++;
  3825.   }
  3826. }
  3827.  
  3828. HTSEXT_API void escape_for_html_print(char* s, char* d) {
  3829.   for( ; *s ; s++) {
  3830.     if (*s == '&') {
  3831.       strcpybuff(d, "&");
  3832.       d += strlen(d);
  3833.     } else {
  3834.       *d++ = *s;
  3835.     }
  3836.   }
  3837.   *d = '\0';
  3838. }
  3839.  
  3840. HTSEXT_API void escape_for_html_print_full(char* s, char* d) {
  3841.   for( ; *s ; s++) {
  3842.     if (*s == '&') {
  3843.       strcpybuff(d, "&");
  3844.       d += strlen(d);
  3845.     } else if (CHAR_HIG(*s)) {
  3846.       sprintf(d, "&#x%02x;", (unsigned char) *s);
  3847.       d += strlen(d);
  3848.     } else {
  3849.       *d++ = *s;
  3850.     }
  3851.   }
  3852.   *d = '\0';
  3853. }
  3854.  
  3855. // concat, concatΦne deux chaines et renvoi le rΘsultat
  3856. // permet d'allΘger grandement le code
  3857. // il faut savoir qu'on ne peut mettre plus de 16 concat() dans une expression
  3858. HTSEXT_API char* concat(char *catbuff,const char* a,const char* b) {
  3859.     if (a != NULL && a[0] != '\0') {
  3860.         strcpybuff(catbuff, a);
  3861.     } else {
  3862.         catbuff[0] = '\0';
  3863.     }
  3864.     if (b != NULL && b[0] != '\0') {
  3865.         strcatbuff(catbuff, b);
  3866.     }
  3867.   return catbuff;
  3868. }
  3869. // conversion fichier / -> antislash
  3870. static char* __fconv(char* a) {
  3871. #if HTS_DOSNAME
  3872.   int i;
  3873.   for(i = 0 ; a[i] != 0 ; i++)
  3874.     if (a[i] == '/')  // Unix-to-DOS style
  3875.       a[i] = '\\';
  3876. #endif
  3877.   return a;
  3878. }
  3879.  
  3880. HTSEXT_API char* fconcat(char *catbuff, const char* a, const char* b) {
  3881.   return __fconv(concat(catbuff,a,b));
  3882. }
  3883. HTSEXT_API char* fconv(char *catbuff, const char* a) {
  3884.   return __fconv(concat(catbuff,a,""));
  3885. }
  3886.  
  3887. /* / et \\ en / */
  3888. static char* __fslash(char* a) {
  3889.   int i;
  3890.   for(i = 0 ; a[i] != 0 ; i++)
  3891.     if (a[i] == '\\')  // convertir
  3892.       a[i] = '/';
  3893.   return a;
  3894. }
  3895. char* fslash(char *catbuff, const char* a) {
  3896.   return __fslash(concat(catbuff,a,NULL));
  3897. }
  3898.  
  3899. // conversion minuscules, avec buffer
  3900. char* convtolower(char *catbuff, const char* a) {
  3901.   strcpybuff(catbuff,a);
  3902.   hts_lowcase(catbuff);  // lower case
  3903.   return catbuff;
  3904. }
  3905.  
  3906. // conversion en minuscules
  3907. void hts_lowcase(char* s) {
  3908.   int i;
  3909.   for(i=0;i<(int) strlen(s);i++)
  3910.     if ((s[i]>='A') && (s[i]<='Z'))
  3911.       s[i]+=('a'-'A');
  3912. }
  3913.  
  3914. // remplacer un caractΦre d'une chaεne dans une autre
  3915. HTS_INLINE void hts_replace(char *s,char from,char to) { 
  3916.   char* a;
  3917.   while ((a=strchr(s,from))!=NULL) {
  3918.     *a=to;
  3919.   }
  3920. }
  3921.  
  3922.  
  3923. // caractΦre espace, guillemets, CR, LF etc..
  3924. /* SECTION OPTIMISEE:
  3925.   #define  is_space(c) (strchr(" \"\x0d\x0a\x09'",c)!=NULL)
  3926.   #define  is_realspace(c) (strchr(" \x0d\x0a\x09\x0c",c)!=NULL)
  3927. */
  3928. /*
  3929. HTS_INLINE int is_space(char c) {
  3930.   if (c==' ')  return 1;  // spc
  3931.   if (c=='"')  return 1;  // quote
  3932.   if (c==10)   return 1;  // lf
  3933.   if (c==13)   return 1;  // cr
  3934.   if (c=='\'') return 1;  // quote
  3935.   //if (c=='`')  return 1;  // backquote      << non
  3936.   if (c==9)    return 1;  // tab
  3937.   return 0;
  3938. }
  3939. */
  3940.  
  3941. // caractΦre espace, CR, LF, TAB
  3942. /*
  3943. HTS_INLINE int is_realspace(char c) {
  3944.   if (c==' ')  return 1;  // spc
  3945.   if (c==10)   return 1;  // lf
  3946.   if (c==13)   return 1;  // cr
  3947.   if (c==9)    return 1;  // tab
  3948.   return 0;
  3949. }
  3950. */
  3951.  
  3952.  
  3953.  
  3954.  
  3955.  
  3956. // deviner type d'un fichier local..
  3957. // ex: fil="toto.gif" -> s="image/gif"
  3958. void guess_httptype(httrackp *opt,char *s,const char *fil) {
  3959.   get_httptype(opt,s, fil, 1);
  3960. }
  3961. // idem
  3962. // flag: 1 si toujours renvoyer un type
  3963. HTSEXT_API void get_httptype(httrackp *opt,char *s,const char *fil,int flag) {
  3964.   // userdef overrides get_httptype
  3965.   if (get_userhttptype(opt, s, fil)) {
  3966.     return ;
  3967.   }
  3968.   // regular tests
  3969.   if (ishtml(opt,fil) == 1) {
  3970.     strcpybuff(s,"text/html");
  3971.   } else {
  3972.     /* Check html -> text/html */
  3973.     const char* a = fil + strlen(fil) - 1;    
  3974.     while ( (*a!='.') && (*a!='/') && (a>fil)) a--;
  3975.     if (*a=='.' && strlen(a) < 32) {
  3976.       int j=0;
  3977.       a++;
  3978.       while(strnotempty(hts_mime[j][1])) {
  3979.         if (strfield2(hts_mime[j][1],a)) {
  3980.           if (hts_mime[j][0][0]!='*') {    // Une correspondance existe
  3981.             strcpybuff(s,hts_mime[j][0]);
  3982.             return;
  3983.           }
  3984.         }
  3985.         j++;
  3986.       }
  3987.       
  3988.       if (flag)
  3989.         sprintf(s,"application/%s",a);
  3990.     } else {
  3991.       if (flag)
  3992.         strcpybuff(s,"application/octet-stream");
  3993.     }
  3994.   }
  3995. }
  3996.  
  3997. // get type of fil (php)
  3998. // s: buffer (text/html) or NULL
  3999. // return: 1 if known by user
  4000. int get_userhttptype(httrackp *opt, char *s, const char *fil) {
  4001.   if (s != NULL) {
  4002.     if (s)
  4003.       s[0]='\0';
  4004.     if (fil == NULL || *fil == '\0')
  4005.       return 0;
  4006. #if 1
  4007.     if (StringLength(opt->mimedefs) > 0) {
  4008.  
  4009.       /* Check --assume foooo/foo/bar.cgi=text/html, then foo/bar.cgi=text/html, then bar.cgi=text/html */
  4010.       /* also: --assume baz,bar,foooo/foo/bar.cgi=text/html */
  4011.       /* start from path begining */
  4012.       do {
  4013.         const char* next;
  4014.         const char* mimedefs = StringBuff(opt->mimedefs);    /* loop through mime definitions : \nfoo=bar\nzoo=baz\n.. */
  4015.         while(*mimedefs != '\0') {
  4016.           const char* segment = fil + 1;
  4017.           if (*mimedefs == '\n') {
  4018.             mimedefs++;
  4019.           }
  4020.           /* compare current segment with user's definition */
  4021.           do {
  4022.             int i;
  4023.             /* check current item */
  4024.             for(i = 0 ; 
  4025.               mimedefs[i] != '\0'           /* end of all defs */
  4026.               && mimedefs[i] != ' '         /* next item in left list */
  4027.               && mimedefs[i] != '='         /* end of left list */
  4028.               && mimedefs[i] != '\n'        /* end of this def (?) */
  4029.               && mimedefs[i] == segment[i]  /* same item */
  4030.               ; i++);
  4031.             /* success */
  4032.             if ( ( mimedefs[i] == '=' || mimedefs[i] == ' ' ) && segment[i] == '\0') {
  4033.               int i2;
  4034.               while(mimedefs[i] != 0 && mimedefs[i] != '\n' && mimedefs[i] != '=') i++;
  4035.               if (mimedefs[i] == '=') {
  4036.                 i++;
  4037.                 for(i2 = 0 ; mimedefs[i + i2] != '\n' && mimedefs[i + i2] != '\0' ; i2++) {
  4038.                   s[i2] = mimedefs[i + i2];
  4039.                 }
  4040.                 s[i2] = '\0';
  4041.                 return 1;   /* SUCCESS! */
  4042.               }
  4043.             }
  4044.             /* next item in list */
  4045.             for(mimedefs += i ; 
  4046.               *mimedefs != '\0' && *mimedefs != '\n' && *mimedefs != '=' && *mimedefs != ' ' ; 
  4047.               mimedefs++);
  4048.             if (*mimedefs == ' ') {
  4049.               mimedefs++;
  4050.             }
  4051.           } while(*mimedefs != '\0' && *mimedefs != '\n' && *mimedefs != '=');
  4052.           /* next user-def */
  4053.           for( ; *mimedefs != '\0' && *mimedefs != '\n' ; mimedefs++);
  4054.         }
  4055.         /* shorten segment */
  4056.         next = strchr(fil + 1, '/');
  4057.         if (next == NULL) {
  4058.           /* ext tests */
  4059.           next = strchr(fil + 1, '.');
  4060.         }
  4061.         fil = next;
  4062.       } while(fil != NULL);
  4063.     }
  4064. #else
  4065.     if (*buffer) {
  4066.       char BIGSTK search[1024];
  4067.       char* detect;
  4068.  
  4069.  
  4070.       sprintf(search,"\n%s=",ext);    // php=text/html
  4071.       detect=strstr(*buffer,search);
  4072.       if (!detect) {
  4073.         sprintf(search,"\n%s\n",ext); // php\ncgi=text/html
  4074.         detect=strstr(*buffer,search);
  4075.       }
  4076.       if (detect) {
  4077.         detect=strchr(detect,'=');
  4078.         if (detect) {
  4079.           detect++;
  4080.           if (s) {
  4081.             char* a;
  4082.             a=strchr(detect,'\n');
  4083.             if (a) {
  4084.               strncatbuff(s,detect,(int) (a - detect));
  4085.             }
  4086.           }
  4087.           return 1;
  4088.         }
  4089.       }
  4090.     }
  4091. #endif
  4092.   }
  4093.   return 0;
  4094. }
  4095. // renvoyer extesion d'un type mime..
  4096. // ex: "image/gif" -> gif
  4097. void give_mimext(char *s,const char *st) {   
  4098.   int ok=0;
  4099.   int j=0;
  4100.   s[0]='\0';
  4101.   while( (!ok) && (strnotempty(hts_mime[j][1])) ) {
  4102.     if (strfield2(hts_mime[j][0],st)) {
  4103.       if (hts_mime[j][1][0]!='*') {    // Une correspondance existe
  4104.         strcpybuff(s,hts_mime[j][1]);
  4105.         ok=1;
  4106.       }
  4107.     }
  4108.     j++;
  4109.   }
  4110.   // wrap "x" mimetypes, such as:
  4111.   // application/x-mp3
  4112.   // or
  4113.   // application/mp3
  4114.   if (!ok) {
  4115.     int p;
  4116.     const char* a=NULL;
  4117.     if ((p=strfield(st,"application/x-")))
  4118.       a=st+p;
  4119.     else if ((p=strfield(st,"application/")))
  4120.       a=st+p;
  4121.     if (a) {
  4122.       if ((int)strlen(a) >= 1) {
  4123.         if ((int)strlen(a) <= 4) {
  4124.           strcpybuff(s,a);
  4125.           ok=1;
  4126.         }
  4127.       }
  4128.     }
  4129.   }
  4130. }
  4131. // extension connue?..
  4132. //  0 : non
  4133. //  1 : oui
  4134. //  2 : html
  4135. HTSEXT_API int is_knowntype(httrackp *opt,const char *fil) {
  4136.     char catbuff[CATBUFF_SIZE];
  4137.   const char *ext;
  4138.   int j=0;
  4139.   if (!fil)
  4140.     return 0;
  4141.   ext = get_ext(catbuff, fil);
  4142.   while(strnotempty(hts_mime[j][1])) {
  4143.     if (strfield2(hts_mime[j][1], ext)) {
  4144.       if (strfield2(hts_mime[j][0], "text/html"))
  4145.         return 2;
  4146.       else
  4147.         return 1;
  4148.     }
  4149.     j++;
  4150.   }
  4151.  
  4152.   // Known by user?
  4153.   return (is_userknowntype(opt,fil));
  4154. }
  4155. // extension : html,gif..
  4156. HTSEXT_API char* get_ext(char *catbuff, const char *fil) {
  4157.   const char *a=fil+strlen(fil)-1;    
  4158.  
  4159.   while ( (*a!='.') && (*a!='/')  && (a>fil)) a--;
  4160.   if (*a=='.') {
  4161.         char fil_noquery[HTS_URLMAXSIZE*2];
  4162.     char* b;
  4163.     fil_noquery[0]='\0';
  4164.     a++;  // pointer sur extension
  4165.     strncatbuff(fil_noquery,a,HTS_URLMAXSIZE);
  4166.     b=strchr(fil_noquery,'?');
  4167.     if (b)
  4168.       *b='\0';
  4169.     return concat(catbuff,fil_noquery,"");
  4170.   }
  4171.   else
  4172.     return "";
  4173. }
  4174. // known type?..
  4175. //  0 : no
  4176. //  1 : yes
  4177. //  2 : html
  4178. // setdefs : set mime buffer:
  4179. //   file=(char*) "asp=text/html\nphp=text/html\n"
  4180. HTSEXT_API int is_userknowntype(httrackp *opt,const char *fil) {
  4181.   char BIGSTK mime[1024];
  4182.   if (!fil)
  4183.     return 0;
  4184.   if (!strnotempty(fil))
  4185.     return 0;
  4186.   mime[0]='\0';
  4187.   get_userhttptype(opt, mime, fil);
  4188.   if (!strnotempty(mime))
  4189.     return 0;
  4190.   else if (strfield2(mime,"text/html"))
  4191.     return 2;
  4192.   else
  4193.     return 1;
  4194. }
  4195.  
  4196. // page dynamique?
  4197. // is_dyntype(get_ext("foo.asp"))
  4198. HTSEXT_API int is_dyntype(const char *fil) {
  4199.   int j=0;
  4200.   if (!fil)
  4201.     return 0;
  4202.   if (!strnotempty(fil))
  4203.     return 0;
  4204.   while(strnotempty(hts_ext_dynamic[j])) {
  4205.     if (strfield2(hts_ext_dynamic[j],fil)) {
  4206.       return 1;
  4207.     }
  4208.     j++;
  4209.   }
  4210.   return 0;
  4211. }
  4212.  
  4213. // types critiques qui ne doivent pas Ωtre changΘs car renvoyΘs par des serveurs qui ne
  4214. // connaissent pas le type
  4215. int may_unknown(httrackp *opt,const char* st) {
  4216.   int j=0;
  4217.   // types mΘdia
  4218.   if (may_be_hypertext_mime(opt,st, "")) {
  4219.     return 1;
  4220.   }
  4221.   while(strnotempty(hts_mime_keep[j])) {
  4222.     if (strfield2(hts_mime_keep[j],st)) {      // trouvΘ
  4223.       return 1;
  4224.     }
  4225.     j++;
  4226.   }    
  4227.   return 0;
  4228. }
  4229.  
  4230.  
  4231. // -- Utils fichiers
  4232.  
  4233. // pretty print for i/o
  4234. void fprintfio(FILE* fp,char* buff,char* prefix) {
  4235.   char nl=1;
  4236.   while(*buff) {
  4237.     switch(*buff) {
  4238.     case 13: break;
  4239.     case 10:
  4240.       fprintf(fp,"\r\n");
  4241.       nl=1;
  4242.     break;
  4243.     default:
  4244.       if (nl)
  4245.         fprintf(fp,prefix);
  4246.       nl=0;
  4247.       fputc(*buff,fp);
  4248.     }
  4249.     buff++;
  4250.   }
  4251. }
  4252.  
  4253. /* Le fichier existe-t-il? (ou est-il accessible?) */
  4254. int fexist(const char* s) {
  4255.     char catbuff[CATBUFF_SIZE];
  4256.   struct stat st;
  4257.   memset(&st, 0, sizeof(st));
  4258.   if (stat(fconv(catbuff,s), &st) == 0) {
  4259.     if (S_ISREG(st.st_mode)) {
  4260.       return 1;
  4261.     }
  4262.   }
  4263.   return 0;
  4264.  
  4265. /* Taille d'un fichier, -1 si n'existe pas */
  4266. /* fp->_cnt ne fonctionne pas sur toute les plate-formes :-(( */
  4267. /* Note: NOT YET READY FOR 64-bit */
  4268. off_t fsize(const char* s) {
  4269.     char catbuff[CATBUFF_SIZE];
  4270.     FILE* fp;
  4271.   if (strnotempty(s)==0)     // nom vide: erreur
  4272.     return -1;
  4273.   fp=fopen(fconv(catbuff,s),"rb");
  4274.   if (fp!=NULL) {
  4275.     off_t i;
  4276.     fseek(fp,0,SEEK_END);
  4277. #ifdef HTS_FSEEKO
  4278.     i=ftello(fp);
  4279. #else
  4280.     i=ftell(fp);
  4281. #endif
  4282.     fclose(fp);
  4283.     return i;
  4284.   } else
  4285.     return -1;
  4286. }
  4287.  
  4288. off_t fpsize(FILE* fp) {
  4289.   off_t oldpos,size;
  4290.   if (!fp)
  4291.     return -1;
  4292. #ifdef HTS_FSEEKO
  4293.   oldpos=ftello(fp);
  4294. #else
  4295.   oldpos=ftell(fp);
  4296. #endif
  4297.   fseek(fp,0,SEEK_END);
  4298. #ifdef HTS_FSEEKO
  4299.   size=ftello(fp);
  4300.   fseeko(fp,oldpos,SEEK_SET);
  4301. #else
  4302.   size=ftell(fp);
  4303.   fseek(fp,oldpos,SEEK_SET);
  4304. #endif
  4305.   return size;
  4306. }
  4307.  
  4308. /* root dir, with ending / */
  4309. typedef struct {
  4310.   char path[1024+4];
  4311.   int init;
  4312. } hts_rootdir_strc;
  4313. HTSEXT_API char* hts_rootdir(char* file) {
  4314.   static hts_rootdir_strc strc = {"", 0};
  4315.   if (file) {
  4316.     if (!strc.init) {
  4317.       strc.path[0]='\0';
  4318.       strc.init=1;
  4319.       if (strnotempty(file)) {
  4320.         char* a;
  4321.         strcpybuff(strc.path,file);
  4322.         while((a=strrchr(strc.path,'\\'))) *a='/';
  4323.         if ((a=strrchr(strc.path,'/'))) {
  4324.           *(a+1)='\0';
  4325.         } else
  4326.           strc.path[0]='\0';
  4327.       }
  4328.       if (!strnotempty(strc.path)) {
  4329.         if( getcwd( strc.path, 1024 ) == NULL )
  4330.             strc.path[0]='\0';
  4331.         else
  4332.           strcatbuff(strc.path,"/");
  4333.       }
  4334.     }
  4335.     return NULL;
  4336.   } else if (strc.init)
  4337.     return strc.path;
  4338.   else
  4339.     return "";
  4340. }
  4341.  
  4342.  
  4343.  
  4344. HTSEXT_API hts_stat_struct HTS_STAT;
  4345. //
  4346. // return  number of downloadable bytes, depending on rate limiter
  4347. // see engine_stats() routine, too
  4348. // this routine works quite well for big files and regular ones, but apparently the rate limiter has
  4349. // some problems with very small files (rate too high)
  4350. LLint check_downloadable_bytes(int rate) {
  4351.   if (rate>0) {
  4352.     TStamp time_now;
  4353.     TStamp elapsed_useconds;
  4354.     LLint bytes_transfered_during_period;
  4355.     LLint left;
  4356.  
  4357.     // get the older timer
  4358.     int id_timer = (HTS_STAT.istat_idlasttimer + 1) % 2;
  4359.  
  4360.     time_now=mtime_local();
  4361.     elapsed_useconds = time_now - HTS_STAT.istat_timestart[id_timer];
  4362.     // NO totally stupid - elapsed_useconds+=1000;      // for the next second, too
  4363.     bytes_transfered_during_period = (HTS_STAT.HTS_TOTAL_RECV-HTS_STAT.istat_bytes[id_timer]);
  4364.     
  4365.     left = ((rate * elapsed_useconds)/1000) - bytes_transfered_during_period;
  4366.     if (left <= 0)
  4367.       left = 0;
  4368.     
  4369.     return left;
  4370.   } else
  4371.     return TAILLE_BUFFER;
  4372. }
  4373.  
  4374. //
  4375. // 0 : OK
  4376. // 1 : slow down
  4377. #if 0
  4378. int HTS_TOTAL_RECV_CHECK(int var) {
  4379.   if (HTS_STAT.HTS_TOTAL_RECV_STATE)
  4380.     return 1;
  4381.     /*
  4382.     {
  4383.     if (HTS_STAT.HTS_TOTAL_RECV_STATE==3) { 
  4384.       var = min(var,32); 
  4385.       Sleep(250); 
  4386.     } else if (HTS_STAT.HTS_TOTAL_RECV_STATE==2) { 
  4387.       var = min(var,256); 
  4388.       Sleep(100); 
  4389.     } else { 
  4390.       var/=2; 
  4391.       if (var<=0) var=1; 
  4392.       Sleep(50); 
  4393.     } 
  4394.   }
  4395.     */
  4396.   return 0;
  4397. }
  4398. #endif
  4399.  
  4400. // Lecture dans buff de size octets au maximum en utilisant la socket r (structure htsblk)
  4401. // returns: 
  4402. // >0 : data received
  4403. // == 0 : not yet data
  4404. // <0: error or no data: READ_ERROR, READ_EOF or READ_TIMEOUT
  4405. HTS_INLINE int hts_read(htsblk* r,char* buff,int size) {
  4406.   int retour;
  4407.   //  return read(soc,buff,size);
  4408.   if (r->is_file) {
  4409. #if HTS_WIDE_DEBUG    
  4410.     DEBUG_W("read(%p, %d, %d)\n" _ (void*) buff _ (int) size _ (int) r->fp);
  4411. #endif
  4412.     if (r->fp)
  4413.       retour = (int)fread(buff,1,size,r->fp);
  4414.     else
  4415.       retour = READ_ERROR;
  4416.   } else {
  4417. #if HTS_WIDE_DEBUG    
  4418.     DEBUG_W("recv(%d, %p, %d)\n" _ (int) r->soc _ (void*) buff _ (int) size);
  4419.     if (r->soc==INVALID_SOCKET)
  4420.       printf("!!WIDE_DEBUG ERROR, soc==INVALID hts_read\n");
  4421. #endif
  4422.     //HTS_TOTAL_RECV_CHECK(size);         // Diminuer au besoin si trop de donnΘes reτues
  4423. #if HTS_USEOPENSSL
  4424.     if (SSL_is_available && r->ssl) {
  4425.       retour = SSL_read(r->ssl_con, buff, size);
  4426.       if (retour <= 0) {
  4427.         int err_code = SSL_get_error(r->ssl_con, retour);
  4428.         if (
  4429.           (err_code == SSL_ERROR_WANT_READ)
  4430.           ||
  4431.           (err_code == SSL_ERROR_WANT_WRITE)
  4432.           ) 
  4433.         {
  4434.           retour = 0;             /* no data yet (ssl cache) */
  4435.         } else if (err_code == SSL_ERROR_ZERO_RETURN) {
  4436.           retour = READ_EOF;             /* completed */
  4437.         } else {
  4438.           retour = READ_ERROR;            /* eof or error */
  4439.         }
  4440.       }
  4441.     } else {
  4442. #endif
  4443.     retour=recv(r->soc,buff,size,0);
  4444.     if (retour == 0) {
  4445.       retour = READ_EOF;
  4446.     } else if (retour < 0) {
  4447.       retour = READ_ERROR;
  4448.     }
  4449.   }
  4450.   if (retour > 0)    // compter flux entrant
  4451.     HTS_STAT.HTS_TOTAL_RECV+=retour;
  4452. #if HTS_USEOPENSSL
  4453.   }
  4454. #endif
  4455. #if HTS_WIDE_DEBUG    
  4456.   DEBUG_W("recv/read done (%d bytes)\n" _ (int) retour);
  4457. #endif
  4458.   return retour;
  4459. }
  4460.  
  4461.  
  4462. // -- Gestion cache DNS --
  4463. // 'RX98
  4464. #if HTS_DNSCACHE
  4465.  
  4466. // 'capsule' contenant uniquement le cache
  4467. t_dnscache* _hts_cache(httrackp *opt) {
  4468.     if (opt->state.dns_cache == NULL) {
  4469.         opt->state.dns_cache = (t_dnscache*)malloct(sizeof(t_dnscache));
  4470.         memset(opt->state.dns_cache, 0, sizeof(t_dnscache));
  4471.     }
  4472.   return opt->state.dns_cache;
  4473. }
  4474. // free the cache
  4475. static void hts_cache_free_(t_dnscache* cache) {
  4476.   if (cache != NULL) {
  4477.     if (cache->n != NULL) {
  4478.       hts_cache_free_(cache->n);
  4479.     }
  4480.     freet(cache);
  4481.   }
  4482. }
  4483. void hts_cache_free(t_dnscache* cache) {
  4484.     if (cache != NULL && cache->n != NULL) {
  4485.         hts_cache_free_(cache->n);
  4486.         cache->n = NULL;
  4487.     }
  4488. }
  4489.  
  4490. // lock le cache dns pour tout opΘration d'ajout
  4491. // plus prudent quand plusieurs threads peuvent Θcrire dedans..
  4492. // -1: status? 0: libΘrer 1:locker
  4493.  
  4494. /* 
  4495.   Simple lock for cache
  4496. */
  4497. htsmutex dns_lock = HTSMUTEX_INIT;
  4498.  
  4499. // routine pour le cache - retour optionnel α donner α chaque fois
  4500. // NULL: nom non encore testΘ dans le cache
  4501. // si h_length==0 alors le nom n'existe pas dans le dns
  4502. t_hostent* _hts_ghbn(t_dnscache* cache,const char* iadr,t_hostent* retour) {
  4503.   t_hostent* ret = NULL;
  4504.   hts_mutexlock(&dns_lock);
  4505.   for(;;) {
  4506.     if (strcmp(cache->iadr,iadr) == 0) {  // ok trouvΘ
  4507.       if (cache->host_length > 0) {  // entrΘe valide
  4508.         if (retour->h_addr_list[0])
  4509.           memcpy(retour->h_addr_list[0], cache->host_addr, cache->host_length);
  4510.         retour->h_length=cache->host_length;
  4511.       } else if (cache->host_length == 0) {  // en cours
  4512.         ret = NULL;
  4513.         break;
  4514.       } else {                    // erreur dans le dns, dΘja vΘrifiΘ
  4515.         if (retour->h_addr_list[0])
  4516.           retour->h_addr_list[0][0]='\0';
  4517.         retour->h_length=0;  // erreur, n'existe pas
  4518.       }
  4519.       ret = retour;
  4520.       break;
  4521.     } else {    // on a pas encore trouvΘ
  4522.       if (cache->n!=NULL) { // chercher encore
  4523.         cache = cache->n;   // suivant!
  4524.       } else {
  4525.         ret = NULL;
  4526.         break;
  4527.       }
  4528.     }    
  4529.   }
  4530.   hts_mutexrelease(&dns_lock);
  4531.   return ret;
  4532. }
  4533.  
  4534. // tester si iadr a dΘja ΘtΘ testΘ (ou en cours de test)
  4535. // 0 non encore
  4536. // 1 ok
  4537. // 2 non prΘsent
  4538. int hts_dnstest(httrackp *opt, const char* _iadr) {
  4539.   int ret = 0;
  4540.   t_dnscache* cache=_hts_cache(opt);  // adresse du cache 
  4541.     char iadr[HTS_URLMAXSIZE*2];
  4542.  
  4543.   // sauter user:pass@ Θventuel
  4544.   strcpybuff(iadr, jump_identification(_iadr));
  4545.   // couper Θventuel :
  4546.   {
  4547.     char *a;
  4548.     if ( (a = jump_toport(iadr)) )
  4549.       *a='\0';
  4550.   }
  4551.  
  4552. #ifdef _WIN32
  4553.   if (inet_addr(iadr)!=INADDR_NONE)  // numΘrique
  4554. #else
  4555.   if (inet_addr(iadr)!=(in_addr_t) -1 )  // numΘrique
  4556. #endif
  4557.     return 1;
  4558.  
  4559.   hts_mutexlock(&dns_lock);
  4560.   for(;;) {
  4561.     if (strcmp(cache->iadr, iadr)==0) {  // ok trouvΘ
  4562.       ret = 1;
  4563.       break;
  4564.     } else {    // on a pas encore trouvΘ
  4565.       if (cache->n!=NULL) { // chercher encore
  4566.         cache=cache->n;   // suivant!
  4567.       } else {
  4568.         ret = 2;    // non prΘsent        
  4569.         break ;
  4570.       }
  4571.     }    
  4572.   }
  4573.   hts_mutexrelease(&dns_lock);
  4574.   return ret;
  4575. }
  4576.  
  4577.  
  4578. HTSEXT_API t_hostent* vxgethostbyname(char* hostname, void* v_buffer) {
  4579.   t_fullhostent* buffer = (t_fullhostent*) v_buffer;
  4580.   /* Clear */
  4581.   fullhostent_init(buffer);
  4582.  
  4583.   /* Protection */
  4584.   if (!strnotempty(hostname)) {
  4585.     return NULL;
  4586.   }
  4587.  
  4588.   /* 
  4589.     Strip [] if any : [3ffe:b80:1234:1::1] 
  4590.     The resolver doesn't seem to handle IP6 addresses in brackets
  4591.   */
  4592.   if ((hostname[0] == '[') && (hostname[strlen(hostname)-1] == ']')) {
  4593.     char BIGSTK tempo[HTS_URLMAXSIZE*2];
  4594.     tempo[0]='\0';
  4595.     strncatbuff(tempo, hostname+1, strlen(hostname)-2);
  4596.     strcpybuff(hostname, tempo);
  4597.   }
  4598.  
  4599.   {
  4600. #if HTS_INET6==0
  4601.   /*
  4602.   ipV4 resolver
  4603.     */
  4604.     t_hostent* hp=gethostbyname(hostname);
  4605.     if (hp!=NULL) {
  4606.       if ( (hp->h_length) && ( ((unsigned int) hp->h_length) <= buffer->addr_maxlen) ) {
  4607.         memcpy(buffer->hp.h_addr_list[0], hp->h_addr_list[0], hp->h_length);
  4608.         buffer->hp.h_length = hp->h_length;
  4609.         return &(buffer->hp);
  4610.       }
  4611.     }
  4612. #else
  4613.     /*
  4614.     ipV6 resolver
  4615.     */
  4616.     /*
  4617.     int error_num=0;
  4618.     t_hostent* hp=getipnodebyname(hostname, AF_INET6, AI_DEFAULT, &error_num);
  4619.     oops, deprecated :(
  4620.     */
  4621.     struct addrinfo* res = NULL;
  4622.     struct addrinfo hints;
  4623.     memset(&hints, 0, sizeof(hints));
  4624.     if (IPV6_resolver == 1)        // V4 only (for bogus V6 entries)
  4625.       hints.ai_family = PF_INET;
  4626.     else if (IPV6_resolver == 2)   // V6 only (for testing V6 only)
  4627.       hints.ai_family = PF_INET6;
  4628.     else                           // V4 + V6
  4629.       hints.ai_family = PF_UNSPEC;
  4630.     hints.ai_socktype = SOCK_STREAM;
  4631.     hints.ai_protocol = IPPROTO_TCP;
  4632.     if (getaddrinfo(hostname, NULL, &hints, &res) == 0) {
  4633.       if (res) {
  4634.         if ( (res->ai_addr) && (res->ai_addrlen) && (res->ai_addrlen <= buffer->addr_maxlen) ) {
  4635.           memcpy(buffer->hp.h_addr_list[0], res->ai_addr, res->ai_addrlen);
  4636.           buffer->hp.h_length = (short) res->ai_addrlen;
  4637.           freeaddrinfo(res);
  4638.           return &(buffer->hp);
  4639.         }
  4640.       }
  4641.     }
  4642.     if (res) {
  4643.       freeaddrinfo(res);
  4644.     }
  4645.     
  4646. #endif
  4647.   }
  4648.   return NULL;
  4649. }
  4650.  
  4651. // cache dns interne α HTS // ** FREE A FAIRE sur la chaine
  4652. t_hostent* hts_gethostbyname(httrackp *opt,const char* _iadr, void* v_buffer) {
  4653.   char BIGSTK iadr[HTS_URLMAXSIZE*2];
  4654.   t_fullhostent* buffer = (t_fullhostent*) v_buffer;
  4655.   t_dnscache* cache=_hts_cache(opt);  // adresse du cache
  4656.   t_hostent* hp;
  4657.  
  4658.   /* Clear */
  4659.   fullhostent_init(buffer);
  4660.  
  4661.   strcpybuff(iadr,jump_identification(_iadr));
  4662.   // couper Θventuel :
  4663.   {
  4664.     char *a;
  4665.     if ( (a=jump_toport(iadr)) )
  4666.       *a='\0';
  4667.   }
  4668.  
  4669.   // effacer structure de retour, crΘer nouvelle
  4670.   /*
  4671.   memset(&host, 0, sizeof(t_hostent));  
  4672.   host.h_addr_list=he;
  4673.   he[0]=NULL;
  4674.   he[1]=NULL;  
  4675.   host.h_length=0;  
  4676.   */
  4677.   cache->iadr[0]='*';
  4678.   cache->iadr[1]='\0';
  4679.   
  4680.   /* get IP from the dns cache */
  4681.   hp = _hts_ghbn(cache, iadr, &buffer->hp);
  4682.   if (hp) {
  4683.     if (hp->h_length>0)
  4684.       return hp;
  4685.     else
  4686.       return NULL;    // entrΘe erronΘe (erreur DNS) dans le DNS
  4687.   } else {  // non prΘsent dans le cache dns, tester
  4688.     t_dnscache* c=cache;
  4689.     while(c->n) c=c->n;    // calculer queue
  4690.     
  4691. #if HTS_WIDE_DEBUG    
  4692.     DEBUG_W("gethostbyname\n");
  4693. #endif      
  4694. #if HDEBUG
  4695.     printf("gethostbyname (not in cache)\n");
  4696. #endif
  4697.     {
  4698.       unsigned long inetaddr;
  4699. #ifdef _WIN32
  4700.       if ((inetaddr=inet_addr(iadr))==INADDR_NONE) {
  4701. #else
  4702.       if ((inetaddr=inet_addr(iadr))==(in_addr_t) -1 ) {
  4703. #endif        
  4704. #if DEBUGDNS 
  4705.         printf("resolving (not cached) %s\n",iadr);
  4706. #endif
  4707.         hp=vxgethostbyname(iadr, buffer);  // calculer IP host
  4708.       } else {     // numΘrique, convertir sans passer par le dns
  4709.         buffer->hp.h_addr_list[0]=(char*) &inetaddr;
  4710.         buffer->hp.h_length=4;
  4711.         hp=&buffer->hp;
  4712.       }
  4713.     }
  4714. #if HTS_WIDE_DEBUG    
  4715.     DEBUG_W("gethostbyname done\n");
  4716. #endif
  4717.     cache->n=(t_dnscache*) calloct(1,sizeof(t_dnscache));
  4718.     if (cache->n!=NULL) {
  4719.       strcpybuff(cache->n->iadr,iadr);
  4720.       if (hp!=NULL) {
  4721.         memcpy(cache->n->host_addr, hp->h_addr_list[0], hp->h_length);
  4722.         cache->n->host_length=hp->h_length;
  4723.       } else {
  4724.         cache->n->host_addr[0]='\0';
  4725.         cache->n->host_length=0;  // non existant dans le dns
  4726.       }
  4727.       cache->n->n=NULL;
  4728.       return hp;
  4729.     } else {  // on peut pas noter, mais on peut renvoyer le rΘsultat
  4730.       return hp;
  4731.     }        
  4732.   }  // retour hp du cache
  4733. }
  4734.  
  4735. #else
  4736. HTS_INLINE t_hostent* hts_gethostbyname(httrackp *opt,char* iadr, t_fullhostent* buffer) {
  4737.   t_hostent* retour;
  4738. #if HTS_WIDE_DEBUG    
  4739.   DEBUG_W("gethostbyname (2)\n");
  4740. #endif
  4741. #if DEBUGDNS 
  4742.     printf("blocking method gethostbyname() in progress for %s\n",iadr);
  4743. #endif
  4744.   retour=vxgethostbyname(jump_identification(iadr), );
  4745. #if HTS_WIDE_DEBUG    
  4746.   DEBUG_W("gethostbyname (2) done\n");
  4747. #endif
  4748.   return retour;
  4749. }
  4750. #endif
  4751.  
  4752.  
  4753. // --- Tracage des mallocs() ---
  4754. #ifdef HTS_TRACE_MALLOC
  4755. //#define htsLocker(A, N) htsLocker(A, N)
  4756. #define htsLocker(A, N) do {} while(0)
  4757. static mlink trmalloc = {NULL,0,0,NULL};
  4758. static int trmalloc_id=0;
  4759. static htsmutex* mallocMutex = NULL;
  4760. static void hts_meminit(void) {
  4761.   //if (mallocMutex == NULL) {
  4762.   //  mallocMutex = calloc(sizeof(*mallocMutex), 1);
  4763.   //  htsLocker(mallocMutex, -999);
  4764.   //}
  4765. }
  4766. void* hts_malloc(size_t len) {
  4767.   void* adr;
  4768.   hts_meminit();
  4769.   htsLocker(mallocMutex, 1);
  4770.   fassert(len > 0);
  4771.   adr = hts_xmalloc(len, 0);
  4772.   htsLocker(mallocMutex, 0);
  4773.   return adr;
  4774. }
  4775. void* hts_calloc(size_t len,size_t len2) {
  4776.   void* adr;
  4777.   hts_meminit();
  4778.   fassert(len > 0);
  4779.   fassert(len2 > 0);
  4780.   htsLocker(mallocMutex, 1);
  4781.   adr = hts_xmalloc(len, len2);
  4782.   htsLocker(mallocMutex, 0);
  4783.   memset(adr, 0, len * len2);
  4784.   return adr;
  4785. }
  4786. void* hts_strdup(char* str) {
  4787.   size_t size = str ? strlen(str) : 0;
  4788.   char* adr = (char*) hts_malloc(size + 1);
  4789.   fassert(adr != NULL);
  4790.   strcpy(adr, str ? str : "");
  4791.   return adr;
  4792. }
  4793. void* hts_xmalloc(size_t len,size_t len2) {
  4794.   mlink* lnk = (mlink*) calloc(1,sizeof(mlink));
  4795.   fassert(lnk != NULL);
  4796.   fassert(len > 0);
  4797.   fassert(len2 >= 0);
  4798.   if (lnk) {
  4799.     void*  r   = NULL;
  4800.     int size, bsize = sizeof(t_htsboundary);
  4801.     if (len2)
  4802.       size = len * len2;
  4803.     else
  4804.       size = len;
  4805.     size += ((bsize - (size % bsize)) % bsize);  /* check alignement */
  4806.     r = malloc(size + bsize*2);
  4807.     fassert(r != NULL);
  4808.     if (r) {
  4809.       * ( (t_htsboundary*) ((char*) r ) ) 
  4810.         = * ( (t_htsboundary*) ( (char*) r + size + bsize ) )
  4811.         = htsboundary;
  4812.       ((char*) r) += bsize;    /* boundary */
  4813.       lnk->adr = r;
  4814.       lnk->len = size;
  4815.       lnk->id = trmalloc_id++;
  4816.       lnk->next = trmalloc.next;
  4817.       trmalloc.next = lnk;
  4818.       return r;
  4819.     } else {
  4820.       free(lnk);
  4821.     }
  4822.   }
  4823.   return NULL;
  4824. }
  4825. void hts_free(void* adr) {
  4826.   mlink* lnk = &trmalloc;
  4827.   int bsize = sizeof(t_htsboundary);
  4828.   fassert(adr != NULL);
  4829.   if (!adr) {
  4830.     return;
  4831.   }
  4832.   htsLocker(mallocMutex, 1);
  4833.   while(lnk->next != NULL) {
  4834.     if (lnk->next->adr == adr) {
  4835.       mlink* blk_free=lnk->next;
  4836.       fassert(blk_free->id != -1);
  4837.       fassert( * ( (t_htsboundary*) ( (char*) adr - bsize ) ) == htsboundary );
  4838.       fassert( * ( (t_htsboundary*) ( (char*) adr + blk_free->len ) ) == htsboundary );
  4839.       lnk->next=lnk->next->next;
  4840.       free((void*) blk_free);
  4841.       //blk_free->id=-1;
  4842.       free((char*) adr - bsize);
  4843.       htsLocker(mallocMutex, 0);
  4844.       return;
  4845.     }
  4846.     lnk = lnk->next;
  4847.     fassert(lnk->next != NULL);
  4848.   }
  4849.   free(adr);
  4850.   htsLocker(mallocMutex, 0);
  4851. }
  4852. void* hts_realloc(void* adr,size_t len) {
  4853.   int bsize = sizeof(t_htsboundary);
  4854.   len += ((bsize - (len % bsize)) % bsize);  /* check alignement */
  4855.   if (adr != NULL) {
  4856.     mlink* lnk = &trmalloc;
  4857.     htsLocker(mallocMutex, 1);
  4858.     while(lnk->next != NULL)  {
  4859.       if (lnk->next->adr==adr) {
  4860.         {
  4861.           mlink* blk_free=lnk->next;
  4862.           fassert(blk_free->id != -1);
  4863.           fassert( * ( (t_htsboundary*) ( (char*) adr - bsize ) ) == htsboundary );
  4864.           fassert( * ( (t_htsboundary*) ( (char*) adr + blk_free->len ) ) == htsboundary );
  4865.         }
  4866.         adr = realloc((char*) adr - bsize, len + bsize * 2);
  4867.         fassert(adr != NULL);
  4868.         lnk->next->adr = (char*) adr + bsize;
  4869.         lnk->next->len = len;
  4870.         * ( (t_htsboundary*) ( (char*) adr ) ) 
  4871.           = * ( (t_htsboundary*) ( (char*) adr + len + bsize) ) 
  4872.           = htsboundary;
  4873.         htsLocker(mallocMutex, 0);
  4874.         return (char*) adr + bsize;
  4875.       }
  4876.       lnk = lnk->next;
  4877.       fassert(lnk->next != NULL);
  4878.     }
  4879.     htsLocker(mallocMutex, 0);
  4880.   }
  4881.   return hts_malloc(len);
  4882. }
  4883. mlink* hts_find(char* adr) {
  4884.   char* stkframe = (char*) &stkframe;
  4885.   mlink* lnk = &trmalloc;
  4886.   int bsize = sizeof(t_htsboundary);
  4887.   fassert(adr != NULL);
  4888.   if (!adr) {
  4889.     return NULL;
  4890.   }
  4891.   htsLocker(mallocMutex, 1);
  4892.   while(lnk->next != NULL) {
  4893.     if (adr >= lnk->next->adr && adr <= lnk->next->adr + lnk->next->len) {   /* found */
  4894.       htsLocker(mallocMutex, 0);
  4895.       return lnk->next;
  4896.     }
  4897.     lnk = lnk->next;
  4898.   }
  4899.   htsLocker(mallocMutex, 0);
  4900.   {
  4901.     int depl = (int) (adr - stkframe);
  4902.     if (depl < 0) depl = -depl;
  4903.     //fassert(depl < 512000);   /* near the stack frame.. doesn't look like malloc but stack variable */
  4904.     return NULL;
  4905.   }
  4906. }
  4907. // check the malloct() and calloct() trace stack
  4908. void  hts_freeall(void) {
  4909.   int bsize = sizeof(t_htsboundary);
  4910.   while(trmalloc.next) {
  4911. #if MEMDEBUG
  4912.     printf("* block %d\t not released: at %d\t (%d\t bytes)\n",trmalloc.next->id,trmalloc.next->adr,trmalloc.next->len);
  4913. #endif
  4914.     if (trmalloc.next->id != -1) {
  4915.       free((char*) trmalloc.next->adr - bsize);
  4916.     }
  4917.   }
  4918. }
  4919. #endif
  4920.  
  4921.  
  4922. // -- divers //
  4923.  
  4924. // cut path and project name
  4925. // patch also initial path
  4926. void cut_path(char* fullpath,char* path,char* pname) {
  4927.   path[0]=pname[0]='\0';
  4928.   if (strnotempty(fullpath)) {
  4929.     if ((fullpath[strlen(fullpath)-1]=='/') || (fullpath[strlen(fullpath)-1]=='\\'))
  4930.       fullpath[strlen(fullpath)-1]='\0';
  4931.     if (strlen(fullpath)>1) {
  4932.       char* a;
  4933.       while( (a=strchr(fullpath,'\\')) ) *a='/';     // remplacer par /
  4934.       a=fullpath+strlen(fullpath)-2;
  4935.       while( (*a!='/') && ( a > fullpath)) a--;
  4936.       if (*a=='/') a++;
  4937.       strcpybuff(pname,a);
  4938.       strncatbuff(path,fullpath,(int) (a - fullpath));
  4939.     }
  4940.   }
  4941. }
  4942.  
  4943.  
  4944.  
  4945. // -- Gestion protocole ftp --
  4946.  
  4947. #ifdef _WIN32
  4948. int ftp_available(void) {
  4949.   return 1;
  4950. }
  4951. #else
  4952. int ftp_available(void) {
  4953.   return 1;   // ok!
  4954.   //return 0;   // SOUS UNIX, PROBLEMESs
  4955. }
  4956. #endif
  4957.  
  4958.  
  4959. int hts_dgb_init = 0;
  4960. FILE* hts_dgb_init_fp = NULL;
  4961. HTSEXT_API void hts_debug(int level) {
  4962.   hts_dgb_init = level;
  4963.   if (hts_dgb_init > 0) {
  4964.     HTS_DBG("hts_debug() called");
  4965.   }
  4966. }
  4967.  
  4968. FILE *hts_dgb_(void) {
  4969.   if (hts_dgb_init_fp == NULL) {
  4970.     if ((hts_dgb_init & 0x80) == 0) {
  4971.       hts_dgb_init_fp = stderr;
  4972.     } else {
  4973. #ifdef _WIN32_WCE
  4974.       hts_dgb_init_fp = fopen("\\Temp\\hts-debug.txt", "wb");
  4975. #else
  4976.       hts_dgb_init_fp = fopen("hts-debug.txt", "wb");
  4977. #endif
  4978.       if (hts_dgb_init_fp != NULL) {
  4979.         fprintf(hts_dgb_init_fp, "* Creating file\r\n");
  4980.       }
  4981.     }
  4982.   }
  4983.   return hts_dgb_init_fp;
  4984. }
  4985.  
  4986. static int hts_init_ok = 0;
  4987. HTSEXT_API int hts_init(void) {
  4988.   const char *dbg_env;
  4989.   /* */
  4990.   if (hts_init_ok)
  4991.     return 1;
  4992.   hts_init_ok = 1;
  4993.  
  4994.   /* enable debugging ? */
  4995.   dbg_env = getenv("HTS_LOG");
  4996.   if (dbg_env != NULL && *dbg_env != 0) {
  4997.     int level = 0;
  4998.     if (sscanf(dbg_env, "%d", &level) == 1) {
  4999.       hts_debug(level);
  5000.     }
  5001.   }
  5002.  
  5003.   HTS_DBG("entering hts_init()");    /* debug */
  5004.  
  5005. #ifdef _WIN32_WCE
  5006. #ifndef HTS_CECOMPAT
  5007.   xceinit(L"");
  5008. #endif
  5009. #endif
  5010.  
  5011.   /* Init threads (lazy init) */
  5012.   htsthread_init();
  5013.  
  5014.   /* Ensure external modules are loaded */
  5015.   HTS_DBG("calling htspe_init()");    /* debug */
  5016.   htspe_init();  /* module load (lazy) */
  5017.  
  5018.   /* MD5 Auto-test */
  5019.   {
  5020.     char digest[32 + 2];
  5021.     const unsigned char* atest = (const unsigned char*)"MD5 Checksum Autotest";
  5022.     digest[0] = '\0';
  5023.     domd5mem(atest, strlen(atest), digest, 1); /* a42ec44369da07ace5ec1d660ba4a69a */
  5024.     if (strcmp(digest, "a42ec44369da07ace5ec1d660ba4a69a") != 0) {
  5025.       int fatal_broken_md5 = 0;
  5026.       assertf(fatal_broken_md5);
  5027.     }
  5028.   }
  5029.  
  5030.   HTS_DBG("initializing SSL");    /* debug */
  5031. #if HTS_USEOPENSSL
  5032.   /*
  5033.   Initialize the OpensSSL library
  5034.   */
  5035.   if (!openssl_ctx && SSL_is_available) {
  5036.     if (SSL_load_error_strings) SSL_load_error_strings();
  5037.     SSL_library_init();
  5038.     ///if (SSL_load_error_strings)  SSL_load_error_strings();
  5039.     //if (ERR_load_crypto_strings) ERR_load_crypto_strings();
  5040.     // if (ERR_load_SSL_strings)    ERR_load_SSL_strings(); ???!!!
  5041.     // OpenSSL_add_all_algorithms();
  5042.     openssl_ctx = SSL_CTX_new(SSLv23_client_method());
  5043.     if (!openssl_ctx) {
  5044.       fprintf(stderr, "fatal: unable to initialize TLS: SSL_CTX_new(SSLv23_client_method)\n");
  5045.       abortLog("unable to initialize TLS: SSL_CTX_new(SSLv23_client_method)");
  5046.       assertf("unable to initialize TLS" == NULL);
  5047.     }
  5048.   }
  5049. #endif
  5050.   
  5051.   HTS_DBG("ending hts_init()");    /* debug */
  5052.   return 1;
  5053. }
  5054.  
  5055. /* will not free thread env. */
  5056. HTSEXT_API int hts_uninit(void) {
  5057.   /* hts_init() is a lazy initializer, with limited a allocation (one or two mutexes) ;
  5058.   we won't free anything here as the .h semantic was never being very clear */
  5059.   return 1;
  5060. }
  5061.  
  5062. HTSEXT_API int hts_uninit_module(void) {
  5063.   if (!hts_init_ok)
  5064.     return 1;
  5065.   htsthread_uninit();
  5066.   htspe_uninit();
  5067.   hts_init_ok = 0;
  5068.   return 1;
  5069. }
  5070.  
  5071. HTSEXT_API int hts_log(httrackp *opt, const char* prefix, const char *msg) {
  5072.   if (opt->log != NULL) {
  5073.     fspc(opt, opt->log, prefix);
  5074.     fprintf(opt->log, "%s"LF, msg);
  5075.     return 0;
  5076.   }
  5077.   return 1;   /* Error */
  5078. }
  5079.  
  5080. HTSEXT_API void set_wrappers(httrackp *opt) {        // LEGACY
  5081. }
  5082.  
  5083. HTSEXT_API int plug_wrapper(httrackp *opt, const char *moduleName, const char* argv) {
  5084.   void* handle = openFunctionLib(moduleName);
  5085.   if (handle != NULL) {
  5086.     t_hts_plug plug = (t_hts_plug) getFunctionPtr(handle, "hts_plug");
  5087.     t_hts_unplug unplug = (t_hts_unplug) getFunctionPtr(handle, "hts_unplug");
  5088.     if (plug != NULL) {
  5089.       int ret = plug(opt, argv);
  5090.       if (hts_dgb_init > 0 && opt->log != NULL) {
  5091.         HTS_DBG("plugged module '%s' (return code=%d)" _ moduleName _ ret);
  5092.       }
  5093.       if (ret == 1) {   /* Success! */
  5094.         opt->libHandles.handles = (htslibhandle*) realloct(opt->libHandles.handles, ( opt->libHandles.count + 1 )*sizeof(htslibhandle));
  5095.         opt->libHandles.handles[opt->libHandles.count].handle = handle;
  5096.         opt->libHandles.handles[opt->libHandles.count].moduleName = strdupt(moduleName);
  5097.         opt->libHandles.count++;
  5098.         return 1;
  5099.       } else {
  5100.         HTS_DBG("* note: error while running entry point 'hts_plug' in %s"LF _ moduleName);
  5101.         if (unplug)
  5102.           unplug(opt);
  5103.       }
  5104.     } else {
  5105.       int last_errno = errno;
  5106.       HTS_DBG("* note: can't find entry point 'hts_plug' in %s: %s"LF _ moduleName _ strerror(last_errno));
  5107.     }
  5108.     closeFunctionLib(handle);
  5109.     return 0;
  5110.   } else {
  5111.     int last_errno = errno;
  5112.     HTS_DBG("* note: can't load %s: %s"LF _ moduleName _ strerror(last_errno));
  5113.   }
  5114.   return -1;
  5115. }
  5116.  
  5117. static void unplug_wrappers(httrackp *opt) {
  5118.   if (opt->libHandles.handles != NULL) {
  5119.     int i;
  5120.     for(i = 0 ; i < opt->libHandles.count ; i++) {
  5121.       if (opt->libHandles.handles[i].handle != NULL) {
  5122.         /* hts_unplug(), the dll exit point (finalizer) */
  5123.         t_hts_unplug unplug = (t_hts_unplug) getFunctionPtr(opt->libHandles.handles[i].handle, "hts_unplug");
  5124.         if (unplug != NULL)
  5125.           unplug(opt);
  5126.         closeFunctionLib(opt->libHandles.handles[i].handle);
  5127.         opt->libHandles.handles[i].handle = NULL;
  5128.       }
  5129.       if (opt->libHandles.handles[i].moduleName != NULL) {
  5130.         freet(opt->libHandles.handles[i].moduleName);
  5131.         opt->libHandles.handles[i].moduleName = NULL;
  5132.       }
  5133.     }
  5134.     freet(opt->libHandles.handles);
  5135.     opt->libHandles.handles = NULL;
  5136.     opt->libHandles.count = 0;
  5137.   }
  5138. }
  5139.  
  5140. int multipleStringMatch(const char *s, const char *match) {
  5141.   int ret = 0;
  5142.   String name = STRING_EMPTY;
  5143.   if (match  == NULL || s == NULL || *s == 0)
  5144.     return 0;
  5145.   for( ; *match != 0 ; match++) {
  5146.     StringClear(name);
  5147.     for( ; *match != 0 && *match != '\n' ; match++) {
  5148.       StringAddchar(name, *match);
  5149.     }
  5150.     if (StringLength(name) > 0 && strstr(s, StringBuff(name)) != NULL) {
  5151.       ret = 1;
  5152.       break ;
  5153.     }
  5154.   }
  5155.   StringFree(name);
  5156.   return ret;
  5157. }
  5158.  
  5159. HTSEXT_API httrackp *hts_create_opt(void) {
  5160. #ifdef _WIN32
  5161.   static const char *defaultModules[] = { 
  5162.     "htsswf", "htsjava", "httrack-plugin", NULL 
  5163.   };
  5164. #else
  5165.   static const char *defaultModules[] = { 
  5166.     "libhtsswf.so.1", "libhtsjava.so.2", "httrack-plugin", NULL 
  5167.   };
  5168. #endif
  5169.   httrackp *opt = malloc(sizeof(httrackp));
  5170.  
  5171.   /* default options */
  5172.   memset(opt, 0, sizeof(httrackp));
  5173.   opt->size_httrackp = sizeof(httrackp);
  5174.  
  5175.   /* mutexes */
  5176.   hts_mutexinit(&opt->state.lock);
  5177.  
  5178.     /* custom wrappers */
  5179.   opt->libHandles.count = 0;
  5180.  
  5181.     /* default settings */
  5182.  
  5183.     opt->wizard=2;   // wizard automatique
  5184.   opt->quiet=0;     // questions
  5185.   //  
  5186.   opt->travel=0;   // mΩme adresse
  5187.   opt->depth=9999; // mirror total par dΘfaut
  5188.   opt->extdepth=0; // mais pas α l'extΘrieur
  5189.   opt->seeker=1;   // down 
  5190.   opt->urlmode=2;  // relatif par dΘfaut
  5191.   opt->debug=0;    // pas de dΘbug en plus
  5192.   opt->getmode=3;  // linear scan
  5193.   opt->maxsite=-1; // taille max site (aucune)
  5194.   opt->maxfile_nonhtml=-1; // taille max fichier non html
  5195.   opt->maxfile_html=-1;    // idem pour html
  5196.   opt->maxsoc=4;     // nbre socket max
  5197.   opt->fragment=-1;  // pas de fragmentation
  5198.   opt->nearlink=0;   // ne pas prendre les liens non-html "adjacents"
  5199.   opt->makeindex=1;  // faire un index
  5200.   opt->kindex=0;     // index 'keyword'
  5201.   opt->delete_old=1; // effacer anciens fichiers
  5202.   opt->makestat=0;  // pas de fichier de stats
  5203.   opt->maketrack=0; // ni de tracking
  5204.   opt->timeout=120; // timeout par dΘfaut (2 minutes)
  5205.   opt->cache=1;     // cache prioritaire
  5206.   opt->shell=0;     // pas de shell par defaut
  5207.   opt->proxy.active=0;    // pas de proxy
  5208.   opt->user_agent_send=1; // envoyer un user-agent
  5209.   StringCopy(opt->user_agent, "Mozilla/4.5 (compatible; HTTrack 3.0x; Windows 98)");
  5210.   StringCopy(opt->referer, "");
  5211.   StringCopy(opt->from, "");
  5212.   opt->savename_83=0;     // noms longs par dΘfaut
  5213.   opt->savename_type=0;   // avec structure originale
  5214.   opt->savename_delayed=2;// hard delayed type (default)
  5215.   opt->delayed_cached=1;  // cached delayed type (default)
  5216.   opt->mimehtml=0;        // pas MIME-html
  5217.   opt->parsejava=HTSPARSE_DEFAULT; // parser classes
  5218.   opt->hostcontrol=0;     // PAS de control host pour timeout et traffic jammer
  5219.   opt->retry=2;           // 2 retry par dΘfaut
  5220.   opt->errpage=1;         // copier ou gΘnΘrer une page d'erreur en cas d'erreur (404 etc.)
  5221.   opt->check_type=1;      // vΘrifier type si inconnu (cgi,asp..) SAUF / considΘrΘ comme html
  5222.   opt->all_in_cache=0;    // ne pas tout stocker en cache
  5223.   opt->robots=2;          // traiter les robots.txt
  5224.   opt->external=0;        // liens externes normaux
  5225.   opt->passprivacy=0;     // mots de passe dans les fichiers
  5226.   opt->includequery=1;    // include query-string par dΘfaut
  5227.   opt->mirror_first_page=0;  // pas mode mirror links
  5228.   opt->accept_cookie=1;   // gΘrer les cookies
  5229.   opt->cookie=NULL;
  5230.   opt->http10=0;          // laisser http/1.1
  5231.   opt->nokeepalive = 0;   // pas keep-alive
  5232.   opt->nocompression=0;   // pas de compression
  5233.   opt->tolerant=0;        // ne pas accepter content-length incorrect
  5234.   opt->parseall=1;        // tout parser (tags inconnus, par exemple)
  5235.   opt->parsedebug=0;      // pas de mode dΘbuggage
  5236.   opt->norecatch=0;       // ne pas reprendre les fichiers effacΘs par l'utilisateur
  5237.   opt->verbosedisplay=0;  // pas d'animation texte
  5238.   opt->sizehack=0;        // size hack
  5239.   opt->urlhack=1;         // url hack (normalizer)
  5240.   StringCopy(opt->footer,HTS_DEFAULT_FOOTER);
  5241.   opt->ftp_proxy=1;       // proxy http pour ftp
  5242.   StringCopy(opt->filelist,"");
  5243.   StringCopy(opt->lang_iso,"en, *");
  5244.   StringCopy(opt->mimedefs,"\n"); // aucun filtre mime (\n IMPORTANT)
  5245.   StringClear(opt->mod_blacklist);
  5246.   //
  5247.   opt->log = stdout;
  5248.   opt->errlog = stderr;
  5249.   opt->flush = 1;         // flush sur les fichiers log
  5250.   //opt->aff_progress=0;
  5251.   opt->keyboard=0;
  5252.   //
  5253.   StringCopy(opt->path_html,"");
  5254.   StringCopy(opt->path_log,"");
  5255.   StringCopy(opt->path_bin,"");
  5256.   //
  5257. #if HTS_SPARE_MEMORY==0
  5258.   opt->maxlink=100000;    // 100,000 liens max par dΘfaut (400Kb)
  5259.   opt->maxfilter=200;     // 200 filtres max par dΘfaut
  5260. #else
  5261.   opt->maxlink=10000;     // 10,000 liens max par dΘfaut (40Kb)
  5262.   opt->maxfilter=50;      // 50 filtres max par dΘfaut
  5263. #endif
  5264.   opt->maxcache=1048576*32;  // a peu prΦs 32Mo en cache max -- OPTION NON PARAMETRABLE POUR L'INSTANT --
  5265.   //opt->maxcache_anticipate=256;  // maximum de liens α anticiper
  5266.   opt->maxtime=-1;        // temps max en secondes
  5267. #if HTS_USEMMS
  5268.     opt->mms_maxtime = 60*3600;        // max time for mms streams (one hour)
  5269. #endif
  5270.   opt->maxrate=25000;     // taux maxi
  5271.   opt->maxconn=5.0;       // nombre connexions/s
  5272.   opt->waittime=-1;       // wait until.. hh*3600+mm*60+ss
  5273.   //
  5274.   opt->exec="";
  5275.   opt->is_update=0;      // not an update (yet)
  5276.   opt->dir_topindex=0;   // do not built top index (yet)
  5277.   //
  5278.   opt->bypass_limits=0;  // enforce limits by default
  5279.   opt->state.stop=0;     // stopper
  5280.   opt->state.exit_xh=0;  // abort
  5281.  
  5282.   /* Alocated buffers */
  5283.  
  5284.     opt->callbacks_fun = (t_hts_htmlcheck_callbacks*) malloct(sizeof(t_hts_htmlcheck_callbacks));
  5285.     memset(opt->callbacks_fun, 0, sizeof(t_hts_htmlcheck_callbacks));
  5286.  
  5287.   /* Preload callbacks : java and flash parser, and the automatic user-defined callback */
  5288.  
  5289.   {
  5290.     int i;
  5291.     for(i = 0 ; defaultModules[i] != NULL ; i++) {
  5292.       int ret = plug_wrapper(opt, defaultModules[i], defaultModules[i]);
  5293.       if (ret == 0) {     /* Module aborted initialization */
  5294.         /* Ignored. */
  5295.       }
  5296.     }
  5297.   }
  5298.  
  5299.     return opt;
  5300. }
  5301.  
  5302. HTSEXT_API void hts_free_opt(httrackp *opt) {
  5303.   if (opt != NULL) {
  5304.  
  5305.     /* Alocated callbacks */
  5306.  
  5307.     if (opt->callbacks_fun != NULL) {
  5308.       int i;
  5309.       t_hts_htmlcheck_callbacks_item *items = (t_hts_htmlcheck_callbacks_item*) opt->callbacks_fun;
  5310.       const int size = (int) sizeof(t_hts_htmlcheck_callbacks) / sizeof(t_hts_htmlcheck_callbacks_item);
  5311.       assertf(sizeof(t_hts_htmlcheck_callbacks_item)*size == sizeof(t_hts_htmlcheck_callbacks));
  5312.  
  5313.       /* Free all linked lists */
  5314.       for(i = 0 ; i < size ; i++) {
  5315.         t_hts_callbackarg *carg, *next_carg;
  5316.         for(carg = items[i].carg ; carg != NULL && (next_carg = carg->prev.carg, carg != NULL) ; carg = next_carg ) {
  5317.           hts_free(carg);
  5318.         }
  5319.       }
  5320.  
  5321.       freet(opt->callbacks_fun);
  5322.       opt->callbacks_fun = NULL;
  5323.     }
  5324.  
  5325.     /* Close library handles */
  5326.     unplug_wrappers(opt);
  5327.  
  5328.     /* Cache */
  5329.     if (opt->state.dns_cache != NULL) {
  5330.       hts_cache_free(opt->state.dns_cache);
  5331.       opt->state.dns_cache = NULL;
  5332.     }
  5333.  
  5334.     /* Cancel chain */
  5335.     if (opt->state.cancel != NULL) {
  5336.       htsoptstatecancel *cancel;
  5337.       for(cancel = opt->state.cancel ; cancel != NULL ; ) {
  5338.         htsoptstatecancel *next = cancel->next;
  5339.         if (cancel->url != NULL) {
  5340.           freet(cancel->url);
  5341.         }
  5342.         freet(cancel);
  5343.         cancel = next;
  5344.       }
  5345.       opt->state.cancel = NULL;
  5346.     }
  5347.  
  5348.     /* Free strings */
  5349.  
  5350.     StringFree(opt->proxy.name);
  5351.     StringFree(opt->proxy.bindhost);
  5352.  
  5353.     StringFree(opt->savename_userdef);
  5354.     StringFree(opt->user_agent);
  5355.     StringFree(opt->referer);
  5356.     StringFree(opt->from);
  5357.     StringFree(opt->lang_iso);
  5358.     StringFree(opt->sys_com);
  5359.     StringFree(opt->mimedefs);
  5360.     StringFree(opt->filelist);
  5361.     StringFree(opt->urllist);
  5362.     StringFree(opt->footer);
  5363.     StringFree(opt->mod_blacklist);
  5364.  
  5365.     StringFree(opt->path_html);
  5366.     StringFree(opt->path_log);
  5367.     StringFree(opt->path_bin);
  5368.  
  5369.     /* mutexes */
  5370.     hts_mutexfree(&opt->state.lock);
  5371.  
  5372.     /* Free structure */
  5373.     free(opt);
  5374.   }
  5375. }
  5376.  
  5377. // defaut wrappers
  5378. static void __cdecl htsdefault_init(t_hts_callbackarg *carg) {
  5379. }
  5380. static void __cdecl htsdefault_uninit(t_hts_callbackarg *carg) {
  5381.   // hts_freevar();
  5382. }
  5383. static int __cdecl htsdefault_start(t_hts_callbackarg *carg, httrackp* opt) {
  5384.   return 1; 
  5385. }
  5386. static int __cdecl htsdefault_chopt(t_hts_callbackarg *carg, httrackp* opt) {
  5387.   return 1;
  5388. }
  5389. static int  __cdecl htsdefault_end(t_hts_callbackarg *carg, httrackp* opt) { 
  5390.   return 1; 
  5391. }
  5392. static int __cdecl htsdefault_preprocesshtml(t_hts_callbackarg *carg, httrackp *opt, char** html,int* len,const char* url_adresse,const char* url_fichier) {
  5393.   return 1;
  5394. }
  5395. static int __cdecl htsdefault_postprocesshtml(t_hts_callbackarg *carg, httrackp *opt, char** html,int* len,const char* url_adresse,const char* url_fichier) {
  5396.   return 1;
  5397. }
  5398. static int __cdecl htsdefault_checkhtml(t_hts_callbackarg *carg, httrackp *opt, char* html,int len,const char* url_adresse,const char* url_fichier) {
  5399.   return 1;
  5400. }
  5401. static int __cdecl htsdefault_loop(t_hts_callbackarg *carg, httrackp *opt, lien_back* back,int back_max,int back_index,int lien_n,int lien_tot,int stat_time,hts_stat_struct* stats) {    // appelΘ α chaque boucle de HTTrack
  5402.   return 1;
  5403. }
  5404. static const char* __cdecl htsdefault_query(t_hts_callbackarg *carg, httrackp *opt, const char* question) {
  5405.   return "";
  5406. }
  5407. static const char* __cdecl htsdefault_query2(t_hts_callbackarg *carg, httrackp *opt, const char* question) {
  5408.   return "";
  5409. }
  5410. static const char* __cdecl htsdefault_query3(t_hts_callbackarg *carg, httrackp *opt, const char* question) {
  5411.   return "";
  5412. }
  5413. static int __cdecl htsdefault_check(t_hts_callbackarg *carg, httrackp *opt, const char* adr,const char* fil,int status) {
  5414.   return -1;
  5415. }
  5416. static int __cdecl htsdefault_check_mime(t_hts_callbackarg *carg, httrackp *opt, const char* adr,const char* fil,const char* mime,int status) {
  5417.   return -1;
  5418. }
  5419. static void __cdecl htsdefault_pause(t_hts_callbackarg *carg, httrackp *opt, const char* lockfile) {
  5420.   while (fexist(lockfile)) {
  5421.     Sleep(1000);
  5422.   }
  5423. }
  5424. static void __cdecl htsdefault_filesave(t_hts_callbackarg *carg, httrackp *opt, const char* file) {
  5425. }
  5426. static void __cdecl htsdefault_filesave2(t_hts_callbackarg *carg, httrackp *opt, const char* adr, const char* file, const char* sav, int is_new, int is_modified, int not_updated) {
  5427. }
  5428. static int __cdecl htsdefault_linkdetected(t_hts_callbackarg *carg, httrackp *opt, char* link) {
  5429.   return 1;
  5430. }
  5431. static int __cdecl htsdefault_linkdetected2(t_hts_callbackarg *carg, httrackp *opt, char* link, const char* start_tag) {
  5432.   return 1;
  5433. }
  5434. static int __cdecl htsdefault_xfrstatus(t_hts_callbackarg *carg, httrackp *opt, lien_back* back) {
  5435.   return 1;
  5436. }
  5437. static int __cdecl htsdefault_savename(t_hts_callbackarg *carg, httrackp *opt, const char* adr_complete,const char* fil_complete,const char* referer_adr,const char* referer_fil,char* save) {
  5438.   return 1;
  5439. }
  5440. static int __cdecl htsdefault_sendhead(t_hts_callbackarg *carg, httrackp *opt, char* buff, const char* adr, const char* fil, const char* referer_adr, const char* referer_fil, htsblk* outgoing) {
  5441.   return 1;
  5442. }
  5443. static int __cdecl htsdefault_receivehead(t_hts_callbackarg *carg, httrackp *opt, char* buff, const char* adr, const char* fil, const char* referer_adr, const char* referer_fil, htsblk* incoming) {
  5444.   return 1;
  5445. }
  5446. static int __cdecl htsdefault_detect(t_hts_callbackarg *carg, httrackp *opt, htsmoduleStruct* str) {
  5447.   return 0;
  5448. }
  5449. static int __cdecl htsdefault_parse(t_hts_callbackarg *carg, httrackp *opt, htsmoduleStruct* str) {
  5450.   return 0;
  5451. }
  5452.  
  5453.  
  5454. /* Default internal dummy callbacks */
  5455. const t_hts_htmlcheck_callbacks default_callbacks = {
  5456.     { htsdefault_init, NULL },
  5457.     { htsdefault_uninit, NULL },
  5458.     { htsdefault_start, NULL },
  5459.     { htsdefault_end, NULL },
  5460.     { htsdefault_chopt, NULL },
  5461.     { htsdefault_preprocesshtml, NULL },
  5462.     { htsdefault_postprocesshtml, NULL },
  5463.     { htsdefault_checkhtml, NULL },
  5464.     { htsdefault_query, NULL },
  5465.     { htsdefault_query2, NULL },
  5466.     { htsdefault_query3, NULL },
  5467.     { htsdefault_loop, NULL },
  5468.     { htsdefault_check, NULL },
  5469.     { htsdefault_check_mime, NULL },
  5470.     { htsdefault_pause, NULL },
  5471.     { htsdefault_filesave, NULL },
  5472.     { htsdefault_filesave2, NULL },
  5473.     { htsdefault_linkdetected, NULL },
  5474.     { htsdefault_linkdetected2, NULL },
  5475.     { htsdefault_xfrstatus, NULL },
  5476.     { htsdefault_savename, NULL },
  5477.     { htsdefault_sendhead, NULL },
  5478.     { htsdefault_receivehead, NULL },
  5479.     { htsdefault_detect, NULL },
  5480.     { htsdefault_parse, NULL }
  5481. };
  5482.  
  5483. #define CHARCAST(A) ( (char*) (A) )
  5484. #define OFFSET_OF(TYPE, MEMBER) ( (size_t) ( CHARCAST(&(((TYPE*) NULL)->MEMBER)) - CHARCAST((TYPE*) NULL) ) )
  5485. #define CALLBACK_REF(name, fun) \
  5486.   { name, OFFSET_OF(t_hts_htmlcheck_callbacks, fun) }
  5487. #define MEMBER_OF(STRUCT, OFFSET, TYPE) ( * ((TYPE*)((char*)(STRUCT) + (OFFSET))) )
  5488.  
  5489. const t_hts_callback_ref default_callbacks_ref[] = {
  5490.     CALLBACK_REF("init", init),
  5491.     CALLBACK_REF("free", uninit),
  5492.     CALLBACK_REF("start", start),
  5493.     CALLBACK_REF("end", end),
  5494.     CALLBACK_REF("change-options", chopt),
  5495.     CALLBACK_REF("preprocess-html", preprocess),
  5496.     CALLBACK_REF("postprocess-html", postprocess),
  5497.     CALLBACK_REF("check-html", check_html),
  5498.     CALLBACK_REF("query", query),
  5499.     CALLBACK_REF("query2", query2),
  5500.     CALLBACK_REF("query3", query3),
  5501.     CALLBACK_REF("loop", loop),
  5502.     CALLBACK_REF("check-link", check_link),
  5503.     CALLBACK_REF("check-mime", check_mime),
  5504.     CALLBACK_REF("pause", pause),
  5505.     CALLBACK_REF("save-file", filesave),
  5506.     CALLBACK_REF("save-file2", filesave2),
  5507.     CALLBACK_REF("link-detected", linkdetected),
  5508.     CALLBACK_REF("link-detected2", linkdetected2),
  5509.     CALLBACK_REF("transfer-status", xfrstatus),
  5510.     CALLBACK_REF("save-name", savename),
  5511.     CALLBACK_REF("send-header", sendhead),
  5512.     CALLBACK_REF("receive-header", receivehead),
  5513.     { NULL, 0 }
  5514. };
  5515.  
  5516. size_t hts_get_callback_offs(const char *name) {
  5517.     const t_hts_callback_ref *ref;
  5518.     for(ref = &default_callbacks_ref[0] ; ref->name != NULL ; ref++) {
  5519.         if (strcmp(name, ref->name) == 0) {
  5520.             return ref->offset;
  5521.         }
  5522.     }
  5523.     return (size_t)(-1);
  5524. }
  5525.  
  5526. int hts_set_callback(t_hts_htmlcheck_callbacks *callbacks, const char *name, void *function) {
  5527.     size_t offs = hts_get_callback_offs(name);
  5528.     if (offs != (size_t) -1) {
  5529.         MEMBER_OF(callbacks, offs, void*) = function;
  5530.         return 0;
  5531.     }
  5532.     return 1;
  5533. }
  5534.  
  5535. void *hts_get_callback(t_hts_htmlcheck_callbacks *callbacks, const char *name) {
  5536.     size_t offs = hts_get_callback_offs(name);
  5537.     if (offs != (size_t) -1) {
  5538.         return MEMBER_OF(callbacks, offs, void*);
  5539.     }
  5540.     return NULL;
  5541. }
  5542.  
  5543. // end defaut wrappers
  5544.  
  5545. /* libc stubs */
  5546.  
  5547. HTSEXT_API char* hts_strdup(const char* str) {
  5548.   return strdup(str);
  5549. }
  5550.  
  5551. HTSEXT_API void* hts_malloc(size_t size) {
  5552.   return malloc(size);
  5553. }
  5554.  
  5555. HTSEXT_API void* hts_realloc(void* data, size_t size) {
  5556.   return realloc(data, size);
  5557. }
  5558.  
  5559. HTSEXT_API void hts_free(void* data) {
  5560.   free(data);
  5561. }
  5562.  
  5563. /* Dummy functions */
  5564. HTSEXT_API int hts_resetvar(void) {
  5565.     return 0;
  5566. }
  5567.  
  5568. // Fin
  5569.  
  5570.